chi*_*tom 42 c# wpf assertions winforms
我在下面编写了一个断言方法Ensure.CurrentlyOnUiThread(),用于检查当前线程是否为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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*key 52
不要用
if(Dispatcher.CurrentDispatcher.Thread == Thread.CurrentThread)
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
Dispatcher.CurrentDispatcher将,如果当前线程没有调度程序,则创建并返回Dispatcher与当前线程关联的新线程.
相反,这样做
Dispatcher dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
if (dispatcher != null)
{
// We know the thread have a dispatcher that we can use.
}
Run Code Online (Sandbox Code Playgroud)
为了确保您拥有正确的调度程序或在正确的线程上,您有以下选项
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
}
}
Run Code Online (Sandbox Code Playgroud)
CheckAccess()并且VerifyAccess()不会出现在intellisense中.
此外,如果你不得不诉诸这些东西,可能是由于糟糕的设计.您应该知道哪些线程运行程序中的代码.
Ian*_*Ian 20
在WinForms中你通常会使用
if(control.InvokeRequired)
{
// Do non UI thread stuff
}
Run Code Online (Sandbox Code Playgroud)
对于WPF
if (!control.Dispatcher.CheckAccess())
{
// Do non UI Thread stuff
}
Run Code Online (Sandbox Code Playgroud)
我可能会写一个使用Generic约束的方法来确定你应该调用哪些.例如
public static bool CurrentlyOnUiThread<T>(T control)
{
if(T is System.Windows.Forms.Control)
{
System.Windows.Forms.Control c = control as System.Windows.Forms.Control;
return !c.InvokeRequired;
}
else if(T is System.Windows.Controls.Control)
{
System.Windows.Controls.Control c = control as System.Windows.Control.Control;
return c.Dispatcher.CheckAccess()
}
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*ský 15
对于WPF:
// You are on WPF UI thread!
if (Thread.CurrentThread == System.Windows.Threading.Dispatcher.CurrentDispatcher.Thread)
Run Code Online (Sandbox Code Playgroud)
对于WinForms:
// You are NOT on WinForms UI thread for this control!
if (someControlOrWindow.InvokeRequired)
Run Code Online (Sandbox Code Playgroud)
Cur*_*tis 11
对于WPF,我使用以下内容:
public static void InvokeIfNecessary (Action action)
{
if (Thread.CurrentThread == Application.Current.Dispatcher.Thread)
action ();
else {
Application.Current.Dispatcher.Invoke(action);
}
}
Run Code Online (Sandbox Code Playgroud)
关键是检查Dispatcher.CurrentDispatcher(它将为您提供当前线程的调度程序),您需要检查当前线程是否与应用程序的调度程序或其他控件匹配.
| 归档时间: |
|
| 查看次数: |
36442 次 |
| 最近记录: |