由于基于任务的异步模式现在是推荐的路线(根据 MSDN @ here和here),我将如何将hello world
下面的简单代码转换为基于任务的异步模式?
让我们假设我对此一无所知Tasks
,并且我试图演示工作人员的输入和输出以及从“主”调用。
class Program
{
static void Main(string[] args)
{
Worker wk = new Worker();
string result = wk.DoWork(1000);
Console.WriteLine(result);
Console.WriteLine("Main says, Hello World!");
Console.ReadLine();
}
}
class Worker
{
public string DoWork(int delay)
{
Console.WriteLine("Worker says, working ...");
Thread.Sleep(delay); // represents the 100ms+ workload
return "Worker says, I'm done! Hello World!";
}
}