-1

我想要異步運行Windows服務中的長時間運行的進程 - 並每3秒鐘輪詢一次進程並使用SignalR進行報告。下面的代碼將(理論上)以事件爲基礎的方式來做到這一點,但我不希望隨着每一次改變而開始進展。.NET 4.5輪詢過程示例請

有人可以請提供一個簡單的例子,說明如何實施這個專門啓動過程和民意調查/報告進展。請記住,我幾年來一直沒有全職開發!

public async Task<string> StartTask(int delay) 
{ 
    var tokenSource = new CancellationTokenSource(); 
    var progress = new Progress<Tuple<Int32, Int32>>(); 

    progress.ProgressChanged += (s, e) => 
    { 
     r2hProcessesProxy.Invoke("DownloadNotify", string.Format("Major={0} - Minor={1}", e.Item1 , e.Item2 )); 
    }; 

    var task = DownloadTask.DoDownload(delay, tokenSource.Token, new Progress<Tuple<Int32,Int32>>(p => new Tuple<Int32, Int32>(0,0))); 

    await task; 

    return "Task result"; 
} 
+0

SignalR內置了支持'IProgress '如果說得容易...... – 2015-02-06 22:24:28

+0

對不起 - 是的,它是用signalR但我需要輪詢異步進程,而不是每次都從異步任務對象中推出報表進度。 – 2015-02-06 22:55:03

+0

我只是不確定如何在此頁面上實現輪詢https://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx – 2015-02-06 23:12:41

回答

0

您可以使用反應式擴展(Rx)來做到這一點。檢查Throttle()方法:https://msdn.microsoft.com/en-us/library/hh229400(v=vs.103).aspx

using System; 
using System.Linq; 
using System.Reactive.Linq; 
using System.Threading.Tasks; 

public class Test 
{ 
    public async Task<string> StartTask(int delay) 
    { 
     var tokenSource = new CancellationTokenSource(); 
     var progress = new Progress<Tuple<Int32, Int32>>(); 

     var observable = Observable.FromEvent<EventHandler<Tuple<Int32, Int32>>, Tuple<Int32, Int32>>(h => progress.ProgressChanged += h, h => progress.ProgressChanged -= h); 
     var throttled = observable.Throttle(TimeSpan.FromSeconds(3)); 

     using (throttled.Subscribe(e => 
     { 
      r2hProcessesProxy.Invoke("DownloadNotify", string.Format("Major={0} - Minor={1}", e.Item1, e.Item2)); 
     })) 
     { 
      await DownloadTask.DoDownload(delay, tokenSource.Token, new Progress<Tuple<Int32, Int32>>(p => new Tuple<Int32, Int32>(0, 0))); 
     } 

     return "result"; 
    } 
} 

檢查http://go.microsoft.com/fwlink/?LinkId=208528更多信息有關RX

+0

Thx - 我將與它 - 但e不是訂閱使用語句中的對象(ieeItem1無效) – 2015-02-07 06:36:49

+0

你是什麼意思?使用語句進行檢查,因爲Subscribe是來自Rx的擴展方法。 – 2015-02-07 10:54:47

+0

哦,是的..對不起深夜很抱歉。 – 2015-02-10 00:33:53