【问题标题】:Async method not calling异步方法未调用
【发布时间】:2015-03-12 19:19:33
【问题描述】:

调用 awaitMethod() 不会打印GetFilmCount()console.printline 的第二次调用,也不会调用awaitMethod() 中的最后一个打印语句。 唯一的输出是第一次调用 GetFilmCount() 时的 Console.printLine()

我在这里做错了吗?想不通它为什么会这样??

public async void awaitMethod()
{
    int count1 = await GetFilmCount(1);
    int count2 = await GetFilmCount(2);

    Console.WriteLine("Number of films {0}, {1} ", count1,count2 );
}

public async Task<int> GetFilmCount(int count)
{
    Console.WriteLine("Count {0} ", count);

    using (MySqlConnection connection = new MySqlConnection(connectionString))
    { 
        connection.Open();

        MySqlCommand cmd = new MySqlCommand("select sleep(5) ; select count(*) from sakila.film", connection);

        return await cmd.ExecuteScalarAsync().ContinueWith(t => {
            return Convert.ToInt32(t.Result);
        });
    }
}

【问题讨论】:

  • 你怎么打电话给awaitMethod

标签: c# .net async-await c#-5.0


【解决方案1】:

您不应该使用 async void,除非它是一个 UI 事件处理程序(似乎并非如此)。

这里可能发生的情况是您没有等待 awaitMethod 完成(您不能等待,因为它是一个 void 方法),因此您的控制台应用程序在其余代码有机会执行之前就结束了.

使用async Taskawait(或调用Wait(),如果它在Main)返回Task

public async Task awaitMethod()
{
    int count1 = await GetFilmCount(1);
    int count2 = await GetFilmCount(2);

    Console.WriteLine("Number of films {0}, {1} ", count1,count2 );
}

【讨论】:

  • 感谢改成调用 p.awaitMethod().Wait(); :)
  • @jtkSource 请注意,您应该只在使用 Main 函数时这样做,使用 UI 应用程序这样做,否则您将锁定您的程序。 (我知道答案中提到过,但这个错误经常犯,我想再说一遍)
  • @ScottChamberlain - 同意!是否真的需要异步模式?现有的库不能实现同样的目标
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 2015-11-28
相关资源
最近更新 更多