7

7月 | 2018 | 炒饭的小站

 3 years ago
source link: https://blog.chaofan.io/archives/2018/07
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
7月 | 2018 | 炒饭的小站

C#中new Task中使用async lambda表达式后start的一个坑

C#中的async/await/Task机制是个非常方便的功能,可以将异步的功能写成像同步一样易懂。在其背后,编译器做了一些脏活,比如将async方法从await的地方切开成多个方法,按顺序在线程池中运行。这其中也暗藏了一些坑,如果不是非常有经验的程序员可能就掉进去了。 比如如下的程序,会输出什么呢?

Task t = new Task(async () =>
    Console.WriteLine("Task t start");
    await Task.Delay(1000);
    Console.WriteLine("Task t end");
t.Start();
Task.Run(async () =>
    Console.WriteLine("Anonymous task start");
    await t;
    Console.WriteLine("Anonymous task end");
Thread.Sleep(1200);

这个程序开了两个Task,第一 […]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK