I'm using a Motorola scanner for a WPF application and it seems that anytime I use the scanner to interact with the UI I get some kind of multithreading issue.
For example:
internal class Scanner
{
...//other functions create string from barcode
...//constructor creates scan event that calls OnBarCodeEvent
public delegate void EventHandler();
public event EventHandler ScanEvent = delegate { };
public string strBarcode { get; set; }
public void OnBarcodeEvent(short eventType, ref string scanData)
{
strBarcode = GetBarcodeFromXml(scanData);
ScanEvent();
}
}
public partial class MainWindow : Window
{
private Scanner scanner;
public MainWindow()
{
InitializeComponent();
scanner = new Scanner();
scanner.ScanEvent += ScanEvent;//create an event for the scanner, ScanEvent() was added
}
public void ScanEvent()
{
var strBarcode = scanner.strBarcode;//gets barcode string from Scanner class
//this is just one example of how I use it
this.Dispatcher.Invoke(new Action(() => { tbUserName.Text = strBarcode; }));
}
}
Now the problem is anytime I want to interact with the UI with anything that I got from the scan event, I have to use this.Dispatcher.Invoke(new Action(() => {...} ));
Anytime that I do anything with the scanner and UI without the Dipatcher.Invoke, I get the error The calling thread cannot access this object because a different thread owns it.
I would like to know if there is a better way to handle the scan event or is this the only way I am going to be able to use the scanner to interact with the UI?
Note: the example I showed is only ONE little example, I use the scanner in all aspects of my application so I'd like not to use the Dispatcher.Invoke.