Asynchronous 测量异步请求中的请求时间
我需要运行多个web请求并测量请求和相应响应之间的时间 使用BackgroundWorker的现有代码和使用TPL库的新代码的两种解决方案都存在以下问题,我无法理解:Asynchronous 测量异步请求中的请求时间,asynchronous,httpwebrequest,benchmarking,stopwatch,Asynchronous,Httpwebrequest,Benchmarking,Stopwatch,我需要运行多个web请求并测量请求和相应响应之间的时间 使用BackgroundWorker的现有代码和使用TPL库的新代码的两种解决方案都存在以下问题,我无法理解: var watch = Stopwatch.StartNew(); queue.Enqueue(Task.Factory .FromAsync<WebResponse>(webRequest.BeginGetResponse, webRequest.EndGetResponse
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)
}
}
},
var-watch=Stopwatch.StartNew();
queue.Enqueue(Task.Factory
.FromAsync(webRequest.BeginGetResponse,webRequest.EndGetResponse,null)
.ContinueWith(任务=>
{
使用(var response=(HttpWebResponse)task.Result)
{
//秒表显示错误的结果
//多次请求监视后。经过的时间达到10秒
//这是错误的
//在控制台应用程序中运行的相同代码可以正确工作
Debug.WriteLine(“{0}\t{1}\t{2}”、response.StatusCode、response.ContentType、watch.appeased);
//此行仅在生产表单应用程序中
如果(EventWebRequestFinished!=null)
{
//更新WinForm GUI元素(添加到listboc)
}
}
},
同样的问题我也使用了
DateTime.Now
方法。如果它都是代码,没有任何静态变量等,问题的原因可能是变量“watch”的闭包。表达式获取变量的第一个值,接下来的所有时间都只使用该值。
尝试通过FromAsync方法的第三个参数“state”发送变量值。我也有同样的问题。