我使用摩托罗拉扫描仪进行WPF应用程序,似乎每次使用扫描仪与UI交互时,我都会遇到某种多线程问题。
例如:
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; }));
}
}
现在问题是我想用扫描事件得到的任何东西与UI进行交互,我必须使用this.Dispatcher.Invoke(new Action(() => {...} ));
如果我在没有Dipatcher.Invoke的情况下对扫描仪和用户界面做任何事情,我会收到错误The calling thread cannot access this object because a different thread owns it.
我想知道是否有更好的方法来处理扫描事件,或者这是我能够使用扫描程序与UI交互的唯一方法吗?
注意:我展示的示例只是一个小例子,我在应用程序的各个方面都使用了扫描程序,因此我不想使用Dispatcher.Invoke。