[英]WP7 BarcodeManager - Invalid cross-thread access
我正在嘗試使用Windows Phone 7 Silverlight ZXing條形碼掃描庫,但遇到一些問題。
我正在使用后台工作者來檢查圖像,但是當我這樣做時:
WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished);
該代碼引發異常:無效的跨線程訪問。
這是我的代碼...
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
ShowImage();
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
imgCapture.Source = bmp;
this.Image = new BitmapImage();
this.Image.SetSource(e.ChosenPhoto);
progressBar.Visibility = System.Windows.Visibility.Visible;
txtStatus.Visibility = System.Windows.Visibility.Collapsed;
worker.RunWorkerAsync();
}
else
ShowMain();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
Thread.Sleep(2000);
WP7BarcodeManager.ScanMode = com.google.zxing.BarcodeFormat.UPC_EAN;
WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished);
}
catch (Exception ex)
{
Debug.WriteLine("Error processing image.", ex);
}
}
我該如何解決?
使用Dispatcher
在UI線程而非后台線程上執行代碼:
Deployment.Current.Dispatcher.BeginInvoke(()=>
{
WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished);
});
有些操作需要在UI線程上運行,而不能在后台線程上運行。
它可能不喜歡在另一個線程上訪問Image對象。 嘗試將圖像傳遞給工作人員:
worker.RunWorkerAsync(this.Image);
在您的工作人員中使用:
WP7BarcodeManager.ScanBarcode((BitmapImage)e.Argument, BarcodeResults_Finished);
圖像在UI線程上創建,在其他線程上不可訪問,除非您將其凍結: http : //msdn.microsoft.com/zh-cn/library/system.windows.freezable.aspx
在photoChooserTask_Completed中,在啟動后台線程之前立即調用Freeze。
this.Image.Freeze();
worker.RunWorkerAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.