“UseTaskFriendlySynchronizationContext"是什么意思? [英] What's the meaning of "UseTaskFriendlySynchronizationContext"?

查看:25
本文介绍了“UseTaskFriendlySynchronizationContext"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

asp.net 4.5 中有一个新的应用设置

There is a new app setting in asp.net 4.5

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

这样的代码可以在asp.net 4.0中运行

code like this can run in 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 中不起作用,当我删除新的应用程序设置时,它又起作用了!

But it doesn't work in asp.net 4.5,and when I remove the new appsetting,it works again!

那么UseTaskFriendlySynchronizationContext"是什么意思?

So what's the meaning of "UseTaskFriendlySynchronizationContext" ?

推荐答案

关于 UseTaskFriendlySynchronizationContext,来自 微软论坛:

这告诉 ASP.NET 使用一个全新的异步管道遵循 CLR 约定以启动异步操作,包括在必要时将线程返回到 ThreadPool.ASP.NET4.0 及以下版本遵循自己的约定,这违背了 CLR 指南,如果未启用该开关,则非常异步方法很容易同步运行、死锁请求或以其他方式不按预期运行.

That tells ASP.NET to use an entirely new asynchronous pipeline which follows CLR conventions for kicking off asynchronous operations, including returning threads to the ThreadPool when necessary. ASP.NET 4.0 and below followed its own conventions which went against CLR guidelines, and if the switch is not enabled it is very easy for asynchronous methods to run synchronously, deadlock the request, or otherwise not behave as expected.

此外,我认为 AsyncOperationManager 适用于桌面应用程序.对于 ASP.NET 应用程序,您应该使用 RegisterAsyncTask 并设置 <%@ Page Async="true"查看此处了解更多详情.

Also, I think AsyncOperationManager is intended for desktop applications. For ASP.NET apps you should be using RegisterAsyncTask and setting <%@ Page Async="true", see here for more details.

因此,使用新的 c# 关键字,您的示例将是:

So using the new c# keywords your example would be:

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);
}

目标是通过发行版支持以下内容,但目前测试版不支持:

The aim is to support the following by release but is not currently supported in the beta:

protected async void Button1_Click(object sender, EventArgs e)
{
    var res = await new WebClient().DownloadStringTaskAsync("http://www.google.com");
    Response.Write(res);
}

这篇关于“UseTaskFriendlySynchronizationContext"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆