這裏是我的問題。
我在一家BlockingCollectionC#WPF從BlockingCollection更新UI源與調度
public void blockingProducer(BitmapImage imgBSource)
{
if (!collection.IsAddingCompleted)
collection.Add(imgBSource);
}
裝載發生在backgroungwork線程負載幾個BitmapImages。
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
String filepath; int imgCount = 0;
for (int i = 1; i < 10; i++)
{
imgCount++;
filepath = "Snap";
filepath += imgCount;
filepath += ".bmp";
this.Dispatcher.BeginInvoke(new Action(() =>
{
label1.Content = "Snap" + imgCount + " loaded.";
}), DispatcherPriority.Normal);
BitmapImage imgSource = new BitmapImage();
imgSource.BeginInit();
imgSource.UriSource = new Uri(filepath, UriKind.Relative);
imgSource.CacheOption = BitmapCacheOption.OnLoad;
imgSource.EndInit();
blockingProducer(imgSource);
}
}
調試代碼的一切,這部分看起來不錯,現在問題就來了......
完成裝載我想通過一個顯示他們在UI一個圖像之後。我使用的是調度員這樣做,但我總是得到的消息告訴我,因爲它屬於一個不同的線程調用Thread不能訪問該對象。
public void display(BlockingCollection<BitmapImage> results)
{
foreach (BitmapImage item in collection.GetConsumingEnumerable())
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.dstSource.Source = item;
Thread.Sleep(250);
}), DispatcherPriority.Background);
}
}
調試指責的錯誤是在這裏
this.dstSource.Source = item;
我想一切,但不能找出什麼是錯的。任何人有任何想法?
嗨,謝謝你的作品。最後一個問題。將圖像加載到BlockingCollection後,我開始顯示它們,但只顯示最後一幅圖像。有什麼想法發生了什麼?謝謝。 – Probst 2013-04-18 13:12:19
這當然是因爲您在傳遞給分派器的委託方法內執行了Sleep調用。你必須在BeginInvoke之前調用它。但是,更好的解決方案是使用[DispatcherTimer](http://msdn.microsoft.com/zh-cn/library/system.windows.threading.dispatchertimer.aspx)逐個顯示圖像。 – Clemens 2013-04-18 15:31:46
嗨克萊門斯,我刪除了睡眠,但它仍然無法正常工作。奇怪的事實是,當我第二次調用加載線程時,圖像被顯示。但是一旦我調用顯示函數,什麼都不會發生。 所以我第一次運行程序只顯示最後一張圖像。從現在起,每次我調用加載線程時,都會顯示圖像,並且當我調用顯示線程時什麼都不會發生。 – Probst 2013-04-18 15:52:54