WPF 使用Dispatcher
来控制对消息泵的访问,而不是让每个控件负责访问 UI 线程。
您应该使用Dispatcher.Invoke
将委托添加到 WPF 应用程序中的 UI 线程。
It's also worth noting that InvokeRequired
is not really needed in a winform app, nor is it something that you should be checking for in a WPF application. You should know that you're not in the UI thread when you call Invoke
. You shouldn't ever be in a situation where a given method is sometimes called from the UI thread and sometimes called from a background thread. Choose one; either always force the caller to invoke to the UI thread before calling a given method (so you don't need to invoke) or assume that the caller won't be in the UI thread when the method is called. It's also worth noting that calling Invoke
when you're already in the UI thread is just fine. There are no errors or problems that will result from an occasional instance of re-invoking the UI thread (there's a very minor performance cost, so just don't add unneeded code for it all over the place).