在WPF中切换到调度程序线程 [英] switching to dispatcher thread in WPF

查看:311
本文介绍了在WPF中切换到调度程序线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此问题的后续操作.

我必须从其他线程更新ObservableCollection.我用以下代码尝试过:

I have to update a ObservableCollection from a different Thread. I tried it with the following Code:

            Thread t = new Thread(  ()=>
         {
             while(true)
             {

                 if (ErrorDetection.ErrorDetectionIO.doErrorDetection() == 1)
                 {
                     dataLine = ErrorDetection.ErrorDetectionIO.getDataLine();

                     if (mainWindow != null)
                     {
                         ISynchronizeInvoke target = mainWindow; // mainWindow needs to be an WindowsForm?
                         target.Invoke(
                            (Action)(() =>
                             {
                                mainWindow.setNewDataLine(dataLine);
                             }
                             ), null);
                     }

                 }
             }

         }  );

         t.IsBackground = true;
         t.Start();

ErrorDetectionIO.doErrorDetection()在c ++/cli .dll中,并调用本机c代码.

ErrorDetectionIO.doErrorDetection() is in a c++/cli .dll and calls native c Code.

setNewDataLine在mainWindow上,并向Observable集合添加一行.

setNewDataLine is on the mainWindow and adds a Line to the Observable Collection.

如果从其他线程调用它,则会导致异常: 这种类型的CollectionView不支持从与Dispatcher线程不同的线程对其SourceCollection进行更改."

If its called from a different Thread it causes an exception: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

问题是ISynchronize Invoke似乎不适用于wpf?出现编译器错误消息,提示mainWindow无法转换为ISynchronizeInvoke.

The Problem is that ISynchronize Invoke does not seem to work with wpf? Threres an compiler error message that mainWindow can´t be converted to ISynchronizeInvoke.

如果我使用 ISynchronizeInvoke target = mainWindow as ISynchronizeInvoke; 可以编译,但是target为null;

if I use ISynchronizeInvoke target = mainWindow as ISynchronizeInvoke; it can be compiled but target is null;

推荐答案

您可以只使用mainWindow.Dispatcher.Invoke而不是尝试转换为ISynchronizeInvoke. Dispatcher.Invoke 将提供正确的为WPF封送邮件.

You can just use mainWindow.Dispatcher.Invoke instead of trying to cast to ISynchronizeInvoke. Dispatcher.Invoke will provide the correct marshaling for WPF.

请注意,.NET 4.5通过设置

Note that .NET 4.5 adds the ability for WPF to handle this automatically by setting BindingOperations.EnableCollectionSynchronization.

这篇关于在WPF中切换到调度程序线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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