简体   繁体   中英

WP7 BarcodeManager - Invalid cross-thread access

I'm trying to use Windows Phone 7 Silverlight ZXing Barcode Scanning Library but I'm having some problems.

I'm using a background worker to check the image, but when I do this:

WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished);

The code throws an exception: Invalid cross-thread access.

Here is my code...

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);
            }
        }

How can I solve this?

Use the Dispatcher to execute the code on the UI thread instead on a background thread:

Deployment.Current.Dispatcher.BeginInvoke(()=>
    { 
         WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished);
   });

Some operations need to run on the UI thread and can't be run on a background thread.

It probably doesn't like accessing your Image object on another thread. Trying passing the image to the worker:

worker.RunWorkerAsync(this.Image);

and in your worker use:

WP7BarcodeManager.ScanBarcode((BitmapImage)e.Argument, BarcodeResults_Finished);

Images are created on the UI thread and are not accessible on onther threads unless you freeze them: http://msdn.microsoft.com/en-us/library/system.windows.freezable.aspx

in photoChooserTask_Completed call Freeze right before starting the background thread.

this.Image.Freeze();
worker.RunWorkerAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM