Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I guess your code relates to Windows Forms.<br/> You call <code>BeginInvoke</code> if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.<br/> 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)</p> <p>If <code>BeginInvoke</code> is called for <code>Delegate</code> type the delegate is just invoked asynchronously.<br/> (<code>Invoke</code> for the sync version.)</p> <p>If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the <code>Task</code> with the according <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx" rel="noreferrer">context</a>. (<code>TaskScheduler.FromCurrentSynchronizationContext()</code>)</p> <p>And to add a little to already said by others: Lambdas can be treated either as anonymous methods or <a href="http://msdn.microsoft.com/ru-ru/library/system.linq.expressions.expression.aspx" rel="noreferrer">expressions</a>.<br/> And that is why you cannot just use <code>var</code> with lambdas: compiler needs a hint.<br/></p> <p><strong>UPDATE:</strong></p> <p>this requires .Net v4.0 and higher</p> <pre><code>// This line must be called in UI thread to get correct scheduler var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext(); // this can be called anywhere var task = new System.Threading.Tasks.Task( () =&gt; someformobj.listBox1.SelectedIndex = 0); // also can be called anywhere. Task will be scheduled for execution. // And *IF I'm not mistaken* can be (or even will be executed synchronously) // if this call is made from GUI thread. (to be checked) task.Start(scheduler); </code></pre> <p>If you started the task from other thread and need to wait for its completition <code>task.Wait()</code> will block calling thread till the end of the task.</p> <p>Read more about tasks <a href="http://www.albahari.com/threading/part5.aspx" rel="noreferrer">here</a>. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload