-1

代码如下。

我想异步调用 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;
        }
    }
4

1 回答 1

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;
}
于 2013-09-20T12:47:19.387 回答