Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Following this link, 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);

Could someone point out where did I go wrong?

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

 public void Update(ColorImageFrame frame);
like image 960
ikel Avatar asked Feb 06 '13 20:02

ikel


People also ask

What does dispatcher invoke do?

Invoke(DispatcherPriority, TimeSpan, Delegate)Executes the specified delegate synchronously at the specified priority and with the specified time-out value on the thread the Dispatcher was created.

Is dispatcher invoke synchronous?

Invoke is synchronous and BeginInvoke is asynchronous. The operation is added to the event queue of the Dispatcher at the specified DispatcherPriority. If multiple BeginInvoke calls are made at the same DispatcherPriority, they will be executed in the order the calls were made.

What is the difference between Invoke and BeginInvoke method in C#?

Invoke : Executes on the UI thread, but calling thread waits for completion before continuing. Control. BeginInvoke : Executes on the UI thread, and calling thread doesn't wait for completion.

Why we use invoke in C#?

Calling Invoke helps us because it allows a background thread to "do stuff" on a UI thread - it works because it doesn't directly call the method, rather it sends a Windows message that says "run this when you get the chance to".


2 Answers

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

ColorImageFrame someFrame = ...;
Dispatcher.Invoke(new Action(() => colorManager.Update(someFrame)));
like image 87
Servy Avatar answered Sep 28 '22 10:09

Servy


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

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[]).

like image 29
Clemens Avatar answered Sep 28 '22 08:09

Clemens