【发布时间】:2012-06-29 21:47:37
【问题描述】:
public class HomeController : Controller
{
public ActionResult Index()
{
Task<string> t = DownloadStringTaskAsync(new Uri("http://www.google.com/search?q=aspnet"));
t.Wait();
string res = t.Result;
return View((object)res);
}
Task<string> DownloadStringTaskAsync(Uri address)
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s, e) => tcs.SetResult(e.Result);
wc.DownloadStringAsync(address);
return tcs.Task;
}
}
操作永远不会返回,请求只会超时。
我们将 TPL 任务用于所有异步操作,并且在切换到框架 4.5 之前必须包装一些 WebClient 的方法。
上述方法DownloadStringTaskAsync 是其中一个包装器的简化版本。
我想不通的是,为什么等待任务会使 aspnet 中的线程死锁,并且在控制台或桌面应用程序中工作正常。
这是死锁线程的样子。
请求线程
[处于睡眠、等待或加入]
mscorlib.dll!System.Threading.Monitor.Wait(object obj, int millisecondsTimeout, bool exitContext) + 0x18 字节 mscorlib.dll!System.Threading.ManualResetEventSlim.Wait(int millisecondsTimeout, System.Threading.CancellationToken cancelToken) + 0x264 字节
mscorlib.dll!System.Threading.Tasks.Task.InternalWait(int millisecondsTimeout, System.Threading.CancellationToken cancelToken) + 0x166 字节 mscorlib.dll!System.Threading.Tasks.Task.Wait(int millisecondsTimeout, System.Threading.CancellationToken cancelToken) + 0x41 字节
mscorlib.dll!System.Threading.Tasks.Task.Wait() + 0xb 字节
TCSProblem.DLL!TCSProblem.Controllers.HomeController.Index() 第 16 行 + 0xa 字节WebClient 线程
[处于睡眠、等待或加入]
mscorlib.dll!System.Threading.Monitor.Enter(object obj, ref bool lockTaken) + 0x14 字节
System.Web.dll!System.Web.AspNetSynchronizationContext.CallCallback(System.Threading.SendOrPostCallback 回调,对象状态) + 0x53 字节
System.Web.dll!System.Web.AspNetSynchronizationContext.Post(System.Threading.SendOrPostCallback 回调,对象状态) + 0x9 字节
System.dll!System.ComponentModel.AsyncOperation.Post(System.Threading.SendOrPostCallback d, object arg) + 0x29 字节
System.dll!System.Net.WebClient.PostProgressChanged(System.ComponentModel.AsyncOperation asyncOp, System.Net.WebClient.ProgressData 进度) + 0x25c 字节
【问题讨论】:
-
您使用异步下载无济于事,反而有害。我猜这段代码取自更大的代码示例?
-
FWIW,如您所写,您可以删除 't.Wait();'因为访问 Result 属性将阻塞,直到任务完成。
标签: c# asp.net-mvc asynchronous task-parallel-library