2016-01-27 40 views
-1

我需要運行多個Web請求並測量請求和相應響應之間的時間。在異步請求中測量請求時間

都使用BackgroundWorker的和新的代碼中使用TPL庫與現有代碼的解決方案有如下的問題,我無法理解:

var watch = Stopwatch.StartNew(); 

queue.Enqueue(Task.Factory 
        .FromAsync<WebResponse>(webRequest.BeginGetResponse, webRequest.EndGetResponse, null) 
        .ContinueWith(task => 
        { 
         using (var response = (HttpWebResponse)task.Result) 
         { 
          // Stopwatch shows wrong results 
          // After multiple request watch.Elapsed time arrives 10 seconds 
          // This is wrong be 
          // The same code running in Console Application works corectly 
          Debug.WriteLine("{0}\t{1}\t{2}", response.StatusCode, response.ContentType, watch.Elapsed); 

          // This lines are only in production WiForms app 
          if (EventWebRequestFinished != null) 
          { 
           // Update WinForm GUI elements (add to listboc) 
          } 
         } 
        }, 

同樣的問題,我也用DateTime.Now方法。

回答

1

如果是全部代碼,沒有任何靜態變量等,問題的原因可能是變量'手錶'的關閉。表達式獲取變量的第一個值,並且所有下一次僅使用此值。 嘗試通過FromAsync方法的第3個參數「狀態」發送變量值。

+0

我有同樣的問題。 – hellboy

+0

我正在嘗試'Thread.Sleep(..)' – hellboy