async/await用法
样才能await/wait)
使用Thread
new Thread(() =>
{
Thread.Sleep(1000);
Console.WriteLine("吃饭");
Thread.Sleep(1000);
Console.WriteLine("睡觉");
Thread.Sleep(1000);
Console.WriteLine("打豆豆");
}).Start();
使用Task
await Task.Run(() =>
{
Thread.Sleep(1000);
Console.WriteLine("吃饭");
Thread.Sleep(1000);
Console.WriteLine("睡觉");
Thread.Sleep(1000);
Console.WriteLine("打豆豆");
});
但是 Task 存在问题:
此时可改写代码:
List tasks = new List();
tasks.Add(Task.Run(() =>
{
Thread.Sleep(1000);
Console.WriteLine("吃饭");
Thread.Sleep(1000);
Console.WriteLine("睡觉");
Thread.Sleep(1000);
Console.WriteLine("打豆豆");
}));
tasks.Add(Task.Run(() =>
{
Thread.Sleep(1000);
Console.WriteLine("吃饭");
Thread.Sleep(1000);
Console.WriteLine("睡觉");
Thread.Sleep(1000);
Console.WriteLine("打豆豆");
}));
Task.WaitAll(tasks.ToArray());
参考: .NET WaitAll - 掘金 (juejin.cn)