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 =>
?
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.)
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.
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 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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With