了解C#中的异步/等待 [英] Understanding async / await in C#
问题描述
我开始在C#5.0中学习异步/等待,但我一点也不了解.我不明白如何将其用于并行性.我已经尝试了以下非常基本的程序:
I'm starting to learn about async / await in C# 5.0, and I don't understand it at all. I don't understand how it can be used for parallelism. I've tried the following very basic program:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Task task1 = Task1();
Task task2 = Task2();
Task.WaitAll(task1, task2);
Debug.WriteLine("Finished main method");
}
public static async Task Task1()
{
await new Task(() => Thread.Sleep(TimeSpan.FromSeconds(5)));
Debug.WriteLine("Finished Task1");
}
public static async Task Task2()
{
await new Task(() => Thread.Sleep(TimeSpan.FromSeconds(10)));
Debug.WriteLine("Finished Task2");
}
}
}
该程序只是阻止对Task.WaitAll()
的调用,并且永远不会结束,但是我不明白为什么.我敢肯定,我只是缺少一些简单的东西,或者只是没有正确的思维模式,而且没有任何博客或MSDN文章对您有所帮助.
This program just blocks on the call to Task.WaitAll()
and never finishes, but I am not understanding why. I'm sure I'm just missing something simple or just don't have the right mental model of this, and none of the blogs or MSDN articles that are out there are helping.
推荐答案
我建议您从我的有关TAP的MSDN官方文档.
正如我在介绍性博客文章中提到的那样,有几个Task
成员是TPL的保留对象,在纯async
代码中没有用. new Task
和Task.Start
应替换为Task.Run
(或TaskFactory.StartNew
).同样,应将Thread.Sleep
替换为Task.Delay
.
As I mention in my intro blog post, there are several Task
members that are holdovers from the TPL and have no use in pure async
code. new Task
and Task.Start
should be replaced with Task.Run
(or TaskFactory.StartNew
). Similarly, Thread.Sleep
should be replaced with Task.Delay
.
最后,我建议您不要使用Task.WaitAll
.您的控制台应用程序应仅在使用Task.WhenAll
的单个Task
上为Wait
.经过所有这些更改,您的代码将如下所示:
Finally, I recommend that you do not use Task.WaitAll
; your Console app should just Wait
on a single Task
which uses Task.WhenAll
. With all these changes, your code would look like:
class Program
{
static void Main(string[] args)
{
MainAsync().Wait();
}
public static async Task MainAsync()
{
Task task1 = Task1();
Task task2 = Task2();
await Task.WhenAll(task1, task2);
Debug.WriteLine("Finished main method");
}
public static async Task Task1()
{
await Task.Delay(5000);
Debug.WriteLine("Finished Task1");
}
public static async Task Task2()
{
await Task.Delay(10000);
Debug.WriteLine("Finished Task2");
}
}
这篇关于了解C#中的异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!