Home > LINQ, WPF > Dispatcher.Invoke (call an anonymous function)

Dispatcher.Invoke (call an anonymous function)

In WPF to execute a code related to UI from a different thread the Dispatcher.Invoke should be used. And to avoid writing an extra delegate function you can use a anonymous function such as:

//Clear the contents of myStackPanel
(Action)delegate { this.myStackPanel.Children.Clear(); }, null);

Stackoverflow.com: You need to tell the compiler what type of delegate to create ; MethodInvoker (2.0) or Action (3.5) are common choices (note they have the same signature); like so:

control.Invoke((MethodInvoker) delegate {this.Text = “Hi”;});

Another option is to write an extension method:

public static void Invoke(this Control control, Action action)


this.Invoke(delegate { this.Text = “hi”; });
// or simce we are using C# 3.0
this.Invoke(() => { this.Text = “hi”; });

You can of course do the same with BeginInvoke:

public static void BeginInvoke(this Control control, Action action)

Reference: http://stackoverflow.com/questions/253138/anonymous-method-in-invoke-call

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: