问题描述
我在下面编写了一个断言方法 Ensure.CurrentlyOnUiThread(),该方法检查当前线程是否为UI线程.
I've written an assertion method Ensure.CurrentlyOnUiThread(), below, that checks that the current thread is a UI thread.
- 检测Winforms UI线程是否可靠?
- 我们的应用程序混合了WPF和Winforms,如何最好地检测有效的WPF UI线程?
- 是否有更好的方法来做到这一点?也许是代码合同?
Ensure.cs
using System.Diagnostics;
using System.Windows.Forms;
public static class Ensure
{
[Conditional("DEBUG")]
public static void CurrentlyOnUiThread()
{
if (!Application.MessageLoop)
{
throw new ThreadStateException("Assertion failed: not on the UI thread");
}
}
}
推荐答案
不使用
if(Dispatcher.CurrentDispatcher.Thread == Thread.CurrentThread)
{
// Do something
}
如果当前线程没有调度程序,则
Dispatcher.CurrentDispatcher
将创建并返回与当前线程关联的新Dispatcher
.
Dispatcher.CurrentDispatcher
will, if the current thread do not have a dispatcher, create and return a new Dispatcher
associated with the current thread.
反而这样做
Dispatcher dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
if (dispatcher != null)
{
// We know the thread have a dispatcher that we can use.
}
为确保您具有正确的调度程序或在正确的线程上,您可以使用以下选项
To be sure you have the correct dispatcher or are on the correct thread you have the following options
Dispatcher _myDispatcher;
public void UnknownThreadCalling()
{
if (_myDispatcher.CheckAccess())
{
// Calling thread is associated with the Dispatcher
}
try
{
_myDispatcher.VerifyAccess();
// Calling thread is associated with the Dispatcher
}
catch (InvalidOperationException)
{
// Thread can't use dispatcher
}
}
CheckAccess()
和VerifyAccess()
不在智能感知中显示.
CheckAccess()
and VerifyAccess()
do not show up in intellisense.
此外,如果您不得不诉诸此类情况,则可能是由于设计不当所致.您应该知道哪些线程在程序中运行什么代码.
Also, if you have to resort to these kinds of things its likely due to bad design. You should know which threads run what code in your program.
这篇关于检测是否在WPF和Winforms中的UI线程上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!