2016-01-27 37 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