【发布时间】:2014-08-23 03:56:57
【问题描述】:
我正在使用以下代码读取网络驱动器上的所有图像并为每个图像填充一个ImageControl,然后将它们显示在屏幕上。
我遇到的问题是,无论将PopulateImages() 设为async 方法,并运行Task.WaitAll,用户界面仍然被锁定,直到所有图像都呈现。
我的async/await 操作有误吗?我需要做什么来解决这个问题?
public MainWindow()
{
InitializeComponent();
Loaded += (s, e) => PopulateImages();
}
private async void PopulateImages()
{
string StartDirectory = @"//path/to/network/folder";
Task.WaitAll(Directory
.EnumerateFiles(StartDirectory)
.Select(filename => Task.Run(async () =>
{
Bitmap resizedImage;
using (var sourceStream = File.Open(filename, FileMode.Open))
{
using (var destinationStream = new MemoryStream())
{
await sourceStream.CopyToAsync(destinationStream);
resizedImage = ResizeImage(new Bitmap(destinationStream), 96, 96);
}
}
Dispatcher.BeginInvoke(new Action(() =>
{
var imgControl = new ImageControl(filename, resizedImage);
stackpanelContainer.Children.Add(imgControl);
}));
})).ToArray());
}
【问题讨论】:
-
Task.WaitAll -
PopulateImages是async,但没有await。这应该会产生一个警告。 -
你也不应该在这里使用
Task.Run,因为你在另一个线程中运行的唯一东西就是你想在UI线程中运行的代码,迫使你不必要地使用Dispatcher,你根本不应该碰它。
标签: c# async-await