now*_*ed. 5 .net c# wpf multithreading dispatcher
这是UserControl我正在使用的.
this.CardHolderName.Content是label在用户控件的UI中.
public partial class PersonCredential : UserControl
{
public PersonCredential()
{
InitializeComponent();
Dispatcher.BeginInvoke( (Action) (() => {
SCLib type = new SCLib();
type.StartMonitoring();
type.CardArrived += (string ATR) => { this.CardHolderName.Content = ATR; };
};
}));
Run Code Online (Sandbox Code Playgroud)
我仍然得到错误," 调用线程无法访问此对象,因为不同的线程拥有它 "即使我正在使用它Dispatcher.BeginInvoke.
Dispatcher使用方式有什么问题吗?}
编辑:我在内容控件中实例化用户控件,代码隐藏是:
public partial class MainWindow : Window
{
PersonCredential personCredential {get;set;}
public MainWindow()
{
InitializeComponent();
var personCredential = new CoffeeShop.PersonCredential();
//create an instance of user control.
this.personCredentials.Content = personCredential;
// assign it to the content control inside the wpf main window
.. // blah blah
}
Run Code Online (Sandbox Code Playgroud)
编辑1:
启动监控代码:
public async void StartMonitoring()
{
// Wait for user to press a key
try
{
this.establishContext();
await Task.Run(new Action(WaitForReaderArrival));
////WaitForReaderArrival();
if (IsReaderArrived())
Run Code Online (Sandbox Code Playgroud)
编辑@DanPuzey 的评论。StartMonitoring已经在另一个线程上进行监视。关键是该CardArrived事件不是从 UI 线程引发的:
public PersonCredential()
{
InitializeComponent();
SCLib type = new SCLib();
type.StartMonitoring();
type.CardArrived += (string ATR) => {
// when card arrives, dispatch back to UI thread
Dispatcher.BeginInvoke(new Action(() => {
this.CardHolderName.Content = ATR;
}));
};
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 .NET 4 或更高版本,请Task.Factory.StartNew()使用new Thread().
| 归档时间: |
|
| 查看次数: |
784 次 |
| 最近记录: |