Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ideally what you want to do, is do as much heavy lifting as possible on a different thread to the UI thread. You then use some strategy to join back onto the UI thread to apply the result of the heavy lifting.</p> <p>The simplest approach I've found is to use a Task with a continuation, using 2 different TaskSchedulers. I think there is an easier way using async/await, but I'm not familiar enough with it to comment with any authority.</p> <p>Using your example:</p> <pre><code>private int? _Woo; public int? Woo { get { if (!_Woo.HasValue) { var task = Task.Factory.StartNew&lt;int&gt;(model.GetWoo, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default()); task.ContinueWith(a =&gt; { _Woo = a.Result; }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext()); } return _Woo; } set { _Woo = value; NotifyPropertyChange("Woo"); } } </code></pre> <p>Note that the heavy lifting task is scheduled using the Default TaskScheduler (meaning it will execute on a thread obtained from the ThreadPool) while the continuation is scheduled using the current synchronization context TaskScheduler (meaning it will execute back on whatever thread originally called Get).</p> <p>Usually I would inject the 2 TaskSchedulers (Background and Foreground/UI) into the ViewModel so that I could control the scheduling strategy for unit tests, but I've just hard referenced Default and FromCurrentSynchronizationContext in the example above.</p> <p><em>(Side Note: I'm not entirely sure what your sample code was trying to accomplish, if anything. I switched it up so that it is now essentially an asynchronous Get. The UI will ask for the value of Woo, which will trigger an asynchronous refresh using a Task and return instantly with its current NULL value. As soon as GetWoo finishes, it will set the value of Woo on the View Model, which will trigger a Property Changed event (on the correct thread), which will cause the UI to update the value of Woo on the screen. I think it shows the concept of doing the heaving lifting off the UI thread anyway.)</em></p>
    singulars
    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.
    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