astef
astef

Reputation: 9488

MVVM - long-running operation without async-await

I want to start long-running operation like requesting a web page from ViewModel, and perform some progress-update operations on my View. Before, I easily achieved this by awaiting my Model's async methods, but in current project I'm restricted with .NET 4.0, so I can't use C#5 features.

What is the recommended way of doing this?

Upvotes: 1

Views: 178

Answers (2)

Mayur Dhingra
Mayur Dhingra

Reputation: 1577

Use this -

Task.Factory.StartNew(() => 
{
   // Code to load web page or any code you want to run asynchronously
}).ContinueWith(task => 
{
   // Code you want to execute on completion of the above synchronous task,
}, UIHelper.GetUITaskScheduler());

wherein the UIHelper class has the following static method -

public class UIHelper
{
   /* Some other methods */

   public static TaskScheduler GetUITaskScheduler()
   {
      TaskScheduler scheduler = null;
      Application.Current.Dispatcher.Invoke(() =>
      {
         scheduler = TaskScheduler.FromCurrentSynchronizationContext();
      });
      return scheduler;
   }    
}

Upvotes: 1

fattikus
fattikus

Reputation: 542

use RX https://rx.codeplex.com/

You can also observe on the SyncronizationContext.Current

Check them out...

Upvotes: 0

Related Questions