【问题标题】:Async/Await - Vicious Circle C# 5.0异步/等待 - 恶性循环 C# 5.0
【发布时间】: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


【解决方案1】:

您可以使用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;
}

【讨论】:

  • 好的,你把填充答案。剩下的呢?
  • 那我为什么要使用 async/await?经典的 Task.Run 可以按照您的建议进行操作。
  • @AhmetAltun:如果你的FooAsync 方法真的像这个例子一样简单,那么在这里使用async/await 是没有意义的。当你有一些异步操作要等待时,你应该只使用await
  • @AhmetAltun 你问这个?在你的问题中,你说你想这样做。如果您没有充分的理由这样做,则不应修改代码。
  • @AhmetAltun: async 专为异步编程而设计。如果您正在进行异步编程,async 非常有用。如果你不是,那就不是。说async“完全没用”(对于同步程序)就像说 ASP.NET “完全没用”(对于桌面应用程序)。
猜你喜欢
  • 1970-01-01
  • 2021-04-15
  • 2017-12-12
  • 2019-07-02
  • 2021-10-18
  • 2021-07-17
  • 2013-01-01
  • 1970-01-01
  • 2014-04-08
相关资源
最近更新 更多