【发布时间】:2019-06-25 16:44:39
【问题描述】:
我正在创建一个照片库应用,我想按类别显示图片。
在正常模式下,一切正常并显示图像。
但是当图像数量变大(300)时,程序会挂起,需要很长时间才能显示。
所以我想使用异步和显示图像。
我使用了以下代码,但没有任何反应,图像也没有显示
int HandleFileAsync()
{
AllofItems.ForEachWithIndex((item, idx) =>
{
var cv = new CoverViewItem();
var contentImg = new Image();
contentImg.Stretch = Stretch.UniformToFill;
contentImg.Source = new BitmapImage(new Uri(item, UriKind.Absolute));
var img = new Image();
img.Source = new BitmapImage(new Uri(item, UriKind.Absolute));
//-< source >-
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(item, UriKind.Absolute);
//< thumbnail >
src.DecodePixelWidth = 160;
src.CacheOption = BitmapCacheOption.OnLoad;
//</ thumbnail >
src.EndInit();
img.Source = src;
//-</ source >-
img.Stretch = Stretch.Uniform;
img.Height = 160;
cv.Header = img;
cv.Tag = item;
cv.Content = contentImg;
cv.Selected += Cv_Selected;
cv.Deselected += Cv_Deselected;
Dispatcher.Invoke(() =>
{
cover.Items.Add(cv);
});
});
return AllofItems.Count();
}
async void Example()
{
// This method runs asynchronously.
int t = await Task.Run(() => HandleFileAsync());
Console.WriteLine("Compute: " + t);
}
private void Listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AllofItems = GetFileList(@"E:\DL\newArtWork\Art\" + listbox.SelectedItem).ToArray();
cover.Items.Clear();
Example();
}
【问题讨论】:
-
您使用调度程序的方式可能是问题,尝试像这样重写您的代码stackoverflow.com/questions/23442543/…
标签: c# wpf asynchronous async-await