从工作线程调用委托时,Application.Current.Dispatcher不执行委托 [英] Application.Current.Dispatcher not excecutes the delegate when its called from worker threads

查看:546
本文介绍了从工作线程调用委托时,Application.Current.Dispatcher不执行委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从工作线程(主线程除外)触发event(loggingEvent)时,以下代码无法正常工作.当从多个线程触发此事件时,所有工作线程都将在此处冻结.

The following code not working properly when event(loggingEvent) triggered from worker threads (other than Main thread). All worker threads gets freezed here when this event triggerd from multiple threads. 

 void OnLoggingEvent(LogItem logItem)
        {
            
            if (Thread.CurrentThread != System.Windows.Application.Current.Dispatcher.Thread)
            {
                
                System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.DataBind,
                    new Action(
                        delegate()
                        {

                            LogMessages.Add(logItem);
                        }));
            }
            else
                logMessages.Add(logItem);
            
        }





推荐答案

>当从多个线程触发此事件时,所有工作线程都将在此处冻结. [...] Dispatcher.Invoke


而不是Dispatcher.Invoke,请使用 Dispatcher.BeginInvoke ;像这样的东西
> All worker threads gets freezed here when this event triggerd from multiple threads. [...] Dispatcher.Invoke


instead of Dispatcher.Invoke use Dispatcher.BeginInvoke; something like this

Dispatcher.BeginInvoke(new Action<LogItem>(li => LogMessages.Add(li)), logItem);


这篇关于从工作线程调用委托时,Application.Current.Dispatcher不执行委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆