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 =>
?
Action
is a Type of Delegate provided by the .NET framework. TheAction
points to a method with no parameters and does not return a value.() =>
is lambda expression syntax. Lambda expressions are not of TypeDelegate
. Invoke requiresDelegate
soAction
can be used to wrap the lambda expression and provide the expectedType
toInvoke()
Invoke
causes saidAction
to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoidExceptions
. For example, if one tries to set theRtf
property on aRichTextBox
when an Invoke is necessary, without first calling Invoke, then aCross-thread operation not valid
exception will be thrown. CheckControl.InvokeRequired
before calling Invoke.BeginInvoke
is the Asynchronous version ofInvoke
. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.I guess your code relates to Windows Forms.
You call
BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If
BeginInvoke
is called forDelegate
type the delegate is just invoked asynchronously.(
Invoke
for the sync version.)If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the
Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use
var
with lambdas: compiler needs a hint.UPDATE:
this requires .Net v4.0 and higher
If you started the task from other thread and need to wait for its completition
task.Wait()
will block calling thread till the end of the task.Read more about tasks here.