How to use BeginInvoke C#

Mohammed Noureldin picture Mohammed Noureldin · Jan 17, 2013 · Viewed 130k times · Source

Could you explain this for me please:

someformobj.BeginInvoke((Action)(() =>
{
    someformobj.listBox1.SelectedIndex = 0;
}));

Could you tell me how can I use begininvoke exactly? What is Action type? Why there is blank brackets ()? And what does this mean =>?

Answer

P.Brian.Mackey picture P.Brian.Mackey · Jan 17, 2013

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.