【发布时间】:2013-09-20 20:47:19
【问题描述】:
代码如下。
我想异步调用 DoLongWork 函数。
但代码最终是同步的,因为 DoLongWork 没有等待任何东西。
在 DoLongWork 函数中不需要等待。因为函数本身是长期运行的。不等待任何资源。
我怎样才能走出这个恶性循环?
class Program
{
static void Main(string[] args)
{
Task<int> task = Foo("Something");
Console.WriteLine("Do it");
Console.WriteLine("Do that");
task.Wait();
Console.WriteLine("Ending All");
}
static async Task<int> Foo(string param)
{
Task<int> lwAsync = DoLongWork(param);
int res = await lwAsync;
return res;
}
static async Task<int> DoLongWork(string param)
{
Console.WriteLine("Long Running Work is starting");
Thread.Sleep(3000); // Simulating long work.
Console.WriteLine("Long Running Work is ending");
return 0;
}
}
【问题讨论】:
-
“我想异步调用 DoLongWork 函数。”为什么?
-
因为它运行时间很长,这是我的问题。
标签: c# asynchronous async-await c#-5.0