Skip to main content
 首页 » 编程设计

c#之异步方法不调用

2024年02月06日12powertoolsteam

调用 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); 
        }); 
    } 
} 

请您参考如下方法:

你不应该使用 async void 除非它是一个 UI 事件处理程序(这似乎不是这种情况)。

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

使用 async Task 而不是 await(如果它在 Main 中则调用 Wait())返回任务:

public async Task awaitMethod() 
{ 
    int count1 = await GetFilmCount(1); 
    int count2 = await GetFilmCount(2); 
 
    Console.WriteLine("Number of films {0}, {1} ", count1,count2 ); 
}