嗨,我試圖創建一個Interactivity.Behavior在後臺加載程序的圖標。以下是代碼,但它給我的調用線程,因爲不同的線程擁有它無法訪問該對象..使用TPL將圖像控件呈現給圖像控件
protected override void OnAttached()
{
base.OnAttached();
if (!string.IsNullOrEmpty(Url))
{
Icon ico = Icon.ExtractAssociatedIcon(Url);
if (ico != null)
{
taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() => {
MemoryStream ms = new MemoryStream();
ico.ToBitmap().Save(ms, ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
return bi;
}).ContinueWith((t) => AssociatedObject.Source = t.Result, taskScheduler);
}
}
}
THanks ..我今天學到了一些新東西...;) 但是...我試着將AssociatedObject.Source = bi放在Task的Action委託中,並使用Task.Factory.StartNew(()=> .. ..,CancellationToken.None,TaskCreationOptions.None,taskScheduler);它的工作原理也是......有什麼區別? – icube
如果使用'TaskScheduler.FromCurrentSynchronizationContext'啓動任務,則在當前線程中運行它。你完全可以不使用任務。 –