Archive

Posts Tagged ‘control.Invoke’

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
this.Dispatcher.Invoke(
(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)
{
control.Invoke((Delegate)action);
}

then:

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)
{
control.BeginInvoke((Delegate)action);
}

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

Advertisements