簡體   English   中英

MVVM-無需異步等待即可長時間運行的操作

[英]MVVM - long-running operation without async-await

我想開始長時間運行的操作,例如從ViewModel請求網頁,並在View上執行一些進度更新操作。 以前,我通過await模型的async方法輕松地實現了這一點,但是在當前項目中,我受.NET 4.0的限制,因此無法使用C#5功能。

建議這樣做的方法是什么?

用這個 -

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());

其中,UIHelper類具有以下靜態方法-

public class UIHelper
{
   /* Some other methods */

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

使用RX https://rx.codeplex.com/

您還可以在SyncronizationContext.Current上進行觀察

去看一下...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM