Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a lot of ways you can do this. A very simple, straightforward one that's been around for a number of versions is to use the <a href="http://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=3&amp;ved=0CGoQFjAC&amp;url=http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx&amp;ei=R84OUKKnK8jX6gGH84D4Dw&amp;usg=AFQjCNFwLYOqQ7vrjVJ7SroICXQH-GDyEQ" rel="nofollow">BackgroundWorker</a>. It is designed for exactly this case. It has a <code>DoWork</code> method that runs in a background thread, and a <code>Completed</code> event that is fired after the work is done which runs in the UI thread (so you don't need to call invoke or anything to update the UI with the results). It even has support built in for reporting progress (the report progress event also runs in the UI thread) so you can easily update a progress bar or status text.</p> <p>MSDN has some <a href="http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx" rel="nofollow">examples</a> as well, and you can find lots more through some simple searches.</p> <p>Another option, made available through C# 4.0, is to use <code>Tasks</code>. You can start a new task which will be run in a background thread, and then you can add a continuation which will be in the UI thread.</p> <p>Here is a simple example:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { Task.Factory.StartNew(() =&gt; doStuffInBackground()) .ContinueWith(task =&gt; updateUI(), TaskScheduler.FromCurrentSynchronizationContext()); } private void updateUI() { throw new NotImplementedException(); } private void doStuffInBackground() { throw new NotImplementedException(); } </code></pre> <p>You can of course do whatever you want in the actual lambdas that I have there, or you could even remove the lambdas and put methods in there directly as long as you ensure the signatures are correct. You could also continue chaining these continuations if you wanted, allowing you to, for example, to task 1, update a label, then do task 2, update a label, etc. The main disadvantage is that it's not good at updating a progress bar frequently inside of a loop, the way a <code>BackgroundWorker</code> can.</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