asp.net 4.5中有一个新的应用程序设置
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
像这样的代码可以在asp.net 4.0中运行
protected void Button1_Click(object sender, EventArgs e)
{
CallAysnc();
}
public void CallAysnc()
{
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(Guid.NewGuid().ToString());
WebClient client = new WebClient();
client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) =>
{
asyncOp.PostOperationCompleted(CallCompleted, e.Result);
};
client.DownloadStringAsync(new Uri("http://www.google.com"));
}
private void CallCompleted(object args)
{
Response.Write(args.ToString());
}
但它在asp.net 4.5中不起作用,当我删除新的appsetting时,它再次有效!
那么“UseTaskFriendlySynchronizationContext”是什么意思?
答案 0 :(得分:69)
关于UseTaskFriendlySynchronizationContext
,来自Microsoft Forums:
告诉ASP.NET使用一个全新的异步管道 遵循CLR约定来启动异步操作, 包括在必要时将线程返回到ThreadPool。 ASP.NET 4.0及以下版本遵循其自身的惯例,违反了CLR指南,如果未启用该开关,则为 非常非常容易让异步方法同步运行,使请求死锁,或者不按预期运行。
另外,我认为AsyncOperationManager
适用于桌面应用程序。对于ASP.NET应用,您应该使用RegisterAsyncTask
并设置<%@ Page Async="true"
,see here for more details。
因此,使用新的c#关键字,您的示例将是:
protected void Button1_Click(object sender, EventArgs e)
{
RegisterAsyncTask(new PageAsyncTask(CallAysnc));
}
private async Task CallAysnc()
{
var res = await new WebClient().DownloadStringTaskAsync("http://www.google.com");
Response.Write(res);
}
目标是在发布时支持以下内容,但目前不支持测试版:
protected async void Button1_Click(object sender, EventArgs e)
{
var res = await new WebClient().DownloadStringTaskAsync("http://www.google.com");
Response.Write(res);
}
答案 1 :(得分:10)
更多细节,引用自MSDN上的ASP.NET 4.5.1 documentation for appSettings:
<强> ASPNET:UseTaskFriendlySynchronizationContext 强>
指定ASP.NET 4.5中异步代码路径的行为方式。
...
如果此键值设置为false [default],则ASP.NET 4.5中的异步代码路径的行为与在ASP.NET 4.0中的行为相同。如果这个键 如果将value设置为true,则ASP.NET 4.5使用已优化的代码路径 用于返回任务的API。设置此兼容性开关是 对于启用WebSockets的应用程序,必须使用基于任务的应用程序 Web窗体页面中的异步,以及某些其他异步 的行为。