Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think trying to switch back and forth between a background thread (for CPU intensive operations or IO operations with no <code>async</code> support) and the UI thread (to manipulate UI controls) is often a sign of bad design. Your calculations and your UI code should be separate.</p> <p>If you're doing this just to notify the UI of some sort of progress, then use <code>IProgress&lt;T&gt;</code>. Any marshaling between threads then becomes the responsibility of the implementation of that interface and you can use <a href="http://msdn.microsoft.com/en-us/library/hh193692.aspx" rel="nofollow"><code>Progress&lt;T&gt;</code></a>, which does it correctly using the <code>SynchronizationContext</code>.</p> <p>If you can't avoid mixing background thread code and UI thread code and your UI work isn't progress reporting (so <code>IProgress&lt;T&gt;</code> won't fit), I would probably enclose each bit of background thread code into its own <code>await Task.Run()</code>, and leave the UI code top level.</p> <p>Your solution of using a single <code>Task.Run()</code> to run the background thread code and then switch to the UI thread using <code>StartNew()</code> with <code>uiScheduler</code> will work too. In that case, some helper methods might be useful, especially if you wanted to use <code>await</code> in the UI code too. (Otherwise, you would have to remember to double <code>await</code> the result of <code>StartNew()</code>)</p> <p>Yet another option would be create a <code>SwitchTo(TaskScheduler)</code> method, which would return a custom awaiter that continues on the given scheduler. Such method was in some of the async CTPs, but it was removed because it was <a href="http://social.msdn.microsoft.com/Forums/en-US/async/thread/078c7e77-5b16-4130-bbf5-c8e6ac82effa#4f40e5ef-bf29-4b1a-a4df-30f8df7bf3fc" rel="nofollow">deemed too dangerous when it comes to handling exceptions</a>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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