多线程WPF应用程序:调度调用。一个更有效的方法?

问题描述:

使用.NET 3.5

大家好,我正在为一个项目一个WPF应用程序,我只是在寻找一点点有关调度和多线程的洞察力。我的程序的一个例子:

Hi Guys, I'm making a WPF application for a project and I was just looking a bit of insight regarding the Dispatcher and multithreading. An example of my program:

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(
                        () =>_aCollection.Add(new Model(aList[i], aSize[i]))));

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(
                        () => _Data.Add(new DataPoint<double, double>(Id, aList[i]))));

 Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(
                        () => _historical[0].Add(aList[i])));



据我所知,WPF不喜欢当另一个线程访问比创建它的其他对象。然而,我想必须有肯定会比做这么多调度员调用一个更好的办法,可能有人请把我在正确的方向上至少(如果有一个更好的解决方案即是)。

I understand that WPF does not like when another thread accessing an object other than the one that created it. However, I was thinking there has to surely be a better way than making so many dispatcher invokes, could someone please push me in the right direction at least (if there is a better solution that is).

干杯,
得利

您可以成为您的通话更简洁开始,即

You can start by being less verbose in your calls, i.e.

Application.Current.Dispatcher.Invoke(() =>_aCollection.Add(new Model(aList[i], aSize[i])));

这是我喜欢使用的另一个技巧是建立一个快捷方式的方法是这样的:

Another trick that I like to use is to make a shortcut method like this:

public static void UiInvoke(Action a)
{
  Application.Current.Dispatcher.Invoke(a);
}



然后,你甚至少做,如:

Then you have even less to do, as in:

UiInvoke(() =>_aCollection.Add(new Model(aList[i], aSize[i])));



使用dispatcher.Invoke()是真的,你是如何让动作返回到UI线程,这可能是其中这些对象(_aCollection)首先被创建。如果有问题的项目没有与UI线程直接互动,那么你可以创建/操纵它们在不同的线程,不再需要使用的调度程序。当然,这取决于你在做什么,这种做法可能会变得更为复杂。

Using dispatcher.Invoke() is really just how you get the action back onto the UI thread, which is probably where these objects (_aCollection) were created in the first place. If the items in question don't have direct interaction with the UI thread, then you can create / manipulate them on a different thread, removing the need to use the dispatcher. Of course this approach could become more complicated depending on what you are doing.