我编写了一个断言方法Ensure.CurrentlyOnUiThread(),如下所示,该方法检查当前线程是否为UI线程。
- 这个方法能可靠地检测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");
}
}
}