gpt4 book ai didi

asp.net - "UseTaskFriendlySynchronizationContext"是什么意思?

转载 作者:行者123 更新时间:2023-12-03 03:29:00 25 4
gpt4 key购买 nike

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

那么“UseTaskFriendlySynchronizationContext”的含义是什么?

最佳答案

关于UseTaskFriendlySynchronizationContext ,来自Microsoft Forums :

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

关于asp.net - "UseTaskFriendlySynchronizationContext"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9562836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com