Dispatcher.Invoke从一个新的线程锁定我的UI [英] Dispatcher.Invoke from a new thread is locking my UI

查看:1290
本文介绍了Dispatcher.Invoke从一个新的线程锁定我的UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WPF,但在我的UI按钮。

i'm using wpf, there's a button on my ui.

当用户点击它,我有一个为运行的新方法,使用的AutoResetEvent一个新的线程循环。

when the user clicks it, i have a for loop that runs a new method, on a new thread using autoresetevent.

在新线程的方法,我使用的标签,让我们叫它lblStatus。我要更新这个线程,这不是在UI上的标签。 。使用WPF,我必须使用Dispatcher.Invoke

in that method on that new thread, i'm using a label, let's call it lblStatus. i want to update that label on this thread that's not on the ui. using wpf, i have to use Dispatcher.Invoke.

这里是我的代码示例:

 Thread thread= new Thread(StartLooking);
 thread.Start();
 _waitHandle.WaitOne();

 private void StartLooking(object value)
{
 if (lblStatus.Dispatcher.Thread == Thread.CurrentThread)
        {
            lblStatus.Content = "Scanning>...";
        }
        else
        {
            lblStatus.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => lblStatus.Content = "Scanning>>>>>")); 
        }
 _waitHandle.Set();
}



程序只是到此为止。它不会改变标签的内容,它返回到我的用户界面,但阻断它。结果
我已经试过

the program just stops here. it doesn't change the content of the label, it returns to my ui, but blocks it.
i've tried

lblStatus.Dispatcher.Invoke(DispatcherPriority.Normal, new LblStatusThreadCheck(lblStatusThreadCheck), "Scanning...");



为好,但这是不是也工作。任何想法?

as well, but that isn't working also. any ideas?

推荐答案

的问题是,你让不可能为这个来执行,由于您使用的调用。

The problem is that you're making it impossible for this to execute, since you're using Invoke.

Dispatcher.Invoke不会返回,直到UI线程处理。但是,你已经通过调用 _waitHandle.WaitOne()阻塞UI线程; ,并且不设置等待句柄直到这个过程之后。这两个有效地引起死锁。

Dispatcher.Invoke will not return until the UI thread processes. However, you've blocked the UI thread by calling _waitHandle.WaitOne();, and don't set the wait handle until AFTER this processes. The two effectively cause a dead lock.

如果您切换此使用的BeginInvoke代替,用户界面将排队元素,等待句柄将设置,则标签将更新。它会工作,并不会阻止的,但是。

If you switch this to use BeginInvoke instead, the UI will queue the element, the wait handle will set, THEN the label will update. It will work and not block, however.

这篇关于Dispatcher.Invoke从一个新的线程锁定我的UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆