我正在玩 C# 的异步等待功能。当我将它与 UI 线程一起使用时,事情会按预期工作。但是当我在非 UI 线程中使用它时,它不能按预期工作。考虑下面的代码
private void Click_Button(object sender, RoutedEventArgs e)
{
var bg = new BackgroundWorker();
bg.DoWork += BgDoWork;
bg.RunWorkerCompleted += BgOnRunWorkerCompleted;
bg.RunWorkerAsync();
}
private void BgOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
}
private async void BgDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
await Method();
}
private static async Task Method()
{
for (int i = int.MinValue; i < int.MaxValue; i++)
{
var http = new HttpClient();
var tsk = await http.GetAsync("http://www.ebay.com");
}
}
当我执行此代码时,后台线程不会等待长时间运行的任务Method
完成。相反,它会立即执行BgOnRunWorkerCompleted
after call Method
。为什么呢?我在这里想念什么?
PS:我对替代方法或正确方法不感兴趣。我想知道在这种情况下幕后实际发生了什么?为什么不等?