代码如下。
我想异步调用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;
}
}
答案 0 :(得分:3)
您可以使用Task.Run
在后台线程上执行同步工作:
// naturally synchronous, so don't use "async"
static 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;
}
static async Task<int> FooAsync(string param)
{
Task<int> lwAsync = Task.Run(() => DoLongWork(param));
int res = await lwAsync;
return res;
}