Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Honestly? Don't use <code>BackgroundWorker</code>. Use TPL manually, <a href="http://msdn.microsoft.com/en-us/library/hh228603.aspx" rel="nofollow">TPL Dataflow</a> or even <a href="http://msdn.microsoft.com/en-us/data/gg577609.aspx" rel="nofollow">Reactive Extensions</a> (Rx) if you want this kind of control.</p> <p>Personally I would use TPL Dataflow and I would setup an <code>TransformBlock&lt;MyObject, MyObject&gt;</code> which you configure with a <code>MaxDegreeOfParallelism</code> that makes sense for you (e.g. you want to process 20 at a time) and then link that back to a UI updating <code>ActionBlock&lt;MyObject&gt;</code> that is configured to run on the UI (<code>Dispatcher</code>) thread. Such code would look something like this...</p> <p><em><strong>Somewhere in your initialization logic, possibly as part of Window constructor (NOTE: must be executed on the main Dispatcher thread to work correctly)</em></strong></p> <pre><code>TransformBlock&lt;MyObject, MyObject&gt; myProcessingBlock = new ActionBlock&lt;MyObject, MyObject&gt;( myObject =&gt; { // ... perform your processing of this object here ... return myObject; }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 20 }); ActionBlock&lt;MyObject&gt; myUINotificationBlock = new ActionBlock&lt;MyObject&gt;( myObject =&gt; { // ... update the UI details for this data here ... }, new ExecutionDataflowBlockOptions { TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext() // must be executed on the Dispatcher block! }); myProcessingBlock.LinkTo(myUINotificationBlock); </code></pre> <p><em><strong>And this is how you would post new work to it:</em></strong></p> <pre><code>MyObject someObjectToProcess = GetSomeObjectToProcess(...); myProcessingBlock.Post(someObjectToProcess); </code></pre> <p>The rest is all handled for you by the magic of the TPL Dataflow Library. Just declare it and set it free. TPL Dataflow even supports <code>async</code> methods, so if you know you're going to be making web service calls you can just use the <code>async</code> keyword on the method you define for the <code>TransformBlock&lt;MyObject, MyObject&gt;</code> like so:</p> <pre><code>TransformBlock&lt;MyObject, MyObject&gt; myProcessingBlock = new ActionBlock&lt;MyObject, MyObject&gt;( async myObject =&gt; { HttpClient someHttpClient = new HttpClient(); HttpResponseMessage responseMessage = await someHttpClient.PostAsync(..., ...); return myObject; }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 20 }); </code></pre> <p>This way you won't even block a CPU thread while the HTTP network call is outstanding which is even more full of win.</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