问题:“Application.Current.Dispatcher.Invoke”应该放在引发事件的工作线程中还是放在处理事件的 UI 代码中?无论哪种方式都可以正常工作,但更好的做法或区别是什么?
在创建新闻行情的 WPF 应用程序中,我通过 Microsoft.Office.Interop.Outlook
和 ItemAdd
事件从新收件箱电子邮件中检索正文,然后引发传递正文的事件。主视图模型按如下方式订阅此事件。在 OutlookReader
类中:
private void OnEmailFoundWithSubjectMatchingFilter(_MailItem item)
{
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
FoundEmailWithSubjectMatchingFilter?.Invoke(this, item.Body);
});
}
并且,在 MainViewModel
类中:
private void HandleEmailFeed(object sender, string e)
{
//Application.Current.Dispatcher.Invoke(() =>
//{
var parser = new MailBodyParser();
AddFeedItem(parser.Parse(e));
//});
}
最佳答案
Should "Application.Current.Dispatcher.Invoke" be put in the worker thread raising an event or in the UI code handling the event?
我会说后者。主要是因为工作线程可能在不知道任何 System.Windows.Application
对象的类库中启动。
因此工作线程应该简单地引发事件,然后客户端应用程序只负责更新最初在其上创建的调度程序线程上的 UI 元素。类库不应该关心甚至不知道任何调度程序。
关于c# - 将 Application.Current.Dispatcher 用于调度程序线程外的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44742487/