Posts Tagged ‘MethodInvoker’

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); 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)