C# Dispatch.Invoke(new Action...) 带参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14738533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:53:00  来源:igfitidea点击:

Dispatch.Invoke( new Action...) with a parameter

c#.netwpfmultithreading

提问by ikel

Previously I had

以前我有

Dispatcher.Invoke(new Action(() => colorManager.Update()));

to update display to WPF from another thread. Due to design, I had to alter the program, and I must pass ColorImageFrame parameter into my ColorStreamManager.Update() method.

从另一个线程更新显示到 WPF。由于设计原因,我不得不更改程序,并且必须将 ColorImageFrame 参数传递到我的 ColorStreamManager.Update() 方法中。

Following thislink, I modified my dispatcher to:

按照链接,我将调度程序修改为:

Dispatcher.Invoke(new Action<ColorStreamManager, ColorImageFrame>((p,v) => p.Update(v)));

It compiles fine but would not run at all. VS2010 says "Parameter count mismatch."In my ColorStreamManager.Update()method I have RaisePropertyChanged(() => Bitmap);

它编译得很好,但根本无法运行。VS2010 显示“参数计数不匹配”。在我的ColorStreamManager.Update()方法中,我有 RaisePropertyChanged(() => Bitmap)

Could someone point out where did I go wrong?

有人能指出我哪里出错了吗?

The signature of ColorStreamManager.Update()method is the following:

ColorStreamManager.Update()方法的签名如下:

 public void Update(ColorImageFrame frame);

采纳答案by Servy

You don't want the action to have parameters, because the Dispatcherisn't going to know what to pass to the method. Instead what you can do is close over the variable:

您不希望操作具有参数,因为Dispatcher它不知道要传递给方法的内容。相反,您可以做的是关闭变量:

ColorImageFrame someFrame = ...;
Dispatcher.Invoke(new Action(() => colorManager.Update(someFrame)));

回答by Clemens

If you call Invokewith an Action<T1, T2>delegate, you need to pass the two Action parameters to the Invoke call:

如果Invoke使用Action<T1, T2>委托调用,则需要将两个 Action 参数传递给 Invoke 调用:

ColorStreamManager colorManager = ...
ColorImageFrame frame = ...

Dispatcher.Invoke(
    new Action<ColorStreamManager, ColorImageFrame>((p,v) => p.Update(v)),
    colorManager,
    frame);

The Invoke overload you're using here is Dispatcher.Invoke(Delegate, Object[]).

您在此处使用的 Invoke 重载是Dispatcher.Invoke(Delegate, Object[]).