在这个函数中等待的地方?

时间:2015-12-02 08:33:24

标签: c# asynchronous

 protected override async void OnNavigatedTo(NavigationEventArgs e)
 {
       base.OnNavigatedTo(e);

       var content = (Content) Application.Current.Resources["NavigationParam"];

       titleName.Text = content.title;
       var uri = new Uri(content.url, UriKind.Absolute);
       imageShow.Source = new BitmapImage(uri);
 }
  

严重级代码说明项目文件行列警告CS1998此   异步方法缺乏等待'运营商并将同步运行。   考虑使用' await'运算符等待非阻塞API调用,   或者等待Task.Run(...)'在后台执行CPU绑定工作   线。 ImageParser C:\ Users \ Johny \ Documents \ Visual Studio   2015 \ Projects \ ImageParser \ ImdbSample \ ItemView.xaml.cs 26 41

2 个答案:

答案 0 :(得分:2)

您不是在等待方法体内的任何异步操作(通过使用await运算符),因此方法定义中的async关键字不是必需的。只需删除它,警告就会消失。

这不会改变方法的语义。正如警告信息明确指出的那样,无论如何它已经同步运行。

答案 1 :(得分:1)

BitmapImage自动异步下载图片 - 您无需再做任何其他事情。删除async关键字,警告就会消失。

如果你在做其他任何事情之前绝对必须等待图片下载,这里有一些代码可以告诉你如何。

// create a task source that we can await on later
TaskCompletionSource<bool> taskSource = new TaskCompletionSource<bool>();

titleName.Text = content.title;

// create an image
var image = new System.Windows.Media.Imaging.BitmapImage();

// subscribe to the images download complete events - set results to true or false depending on if the download finish ok.
image.DownloadCompleted += (sender, args) => taskSource.TrySetResult(true);
                image.DownloadFailed += (sender, args) => taskSource.TrySetResult(false);

// set the uri to start the download
image.UriSource = new Uri(content.url, UriKind.Absolute);

// await the task to extract the result    
bool wasDownloadSuccessful = await taskSource.Task;