Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

asp.net - What's the meaning of "UseTaskFriendlySynchronizationContext"?

There is a new app setting in asp.net 4.5

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

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

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

So what's the meaning of "UseTaskFriendlySynchronizationContext" ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Regarding UseTaskFriendlySynchronizationContext, from 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.

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...