Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use BeginInvoke C#

Tags:

c#

begininvoke

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 =>?

like image 422
Mohammed Noureldin Avatar asked Jan 17 '13 21:01

Mohammed Noureldin


People also ask

How to use BeginInvoke c#?

You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases. If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously. ( Invoke for the sync version.)

How does BeginInvoke work?

The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that you want to execute asynchronously, plus two additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes.

What is Dispatcher BeginInvoke?

BeginInvoke(DispatcherPriority, Delegate, Object) Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.

What is up with BeginInvoke?

What does BeginInvoke do? According to MSDN, Control. BeginInvoke "Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on". It basically takes a delegate and runs it on the thread that created the control on which you called BeginInvoke .


1 Answers

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.

like image 180
P.Brian.Mackey Avatar answered Oct 12 '22 18:10

P.Brian.Mackey