IT박스

“UseTaskFriendlySynchronizationContext”의 의미는 무엇입니까?

itboxs 2020. 11. 21. 14:19

“UseTaskFriendlySynchronizationContext”의 의미는 무엇입니까?


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"의 의미는 무엇입니까?


에 관해서 UseTaskFriendlySynchronizationContextMicrosoft 포럼에서 :

이는 ASP.NET이 필요시 ThreadPool로 스레드를 반환하는 것을 포함하여 비동기 작업을 시작하기위한 CLR 규칙을 따르는 완전히 새로운 비동기 파이프 라인을 사용하도록 지시합니다. ASP.NET 4.0 이하에서는 CLR 지침에 위배되는 자체 규칙을 따랐으며, 스위치가 활성화되지 않은 경우 비동기 메서드가 동 기적으로 실행되거나 요청이 교착 상태가되거나 예상대로 작동하지 않는 것이 매우 쉽습니다.

또한 AsyncOperationManager데스크톱 애플리케이션 용 이라고 생각 합니다. ASP.NET이 사용되어야하는 앱 RegisterAsyncTask과 설정 <%@ Page Async="true", 자세한 내용은 여기를 참조 .

따라서 새 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);
}

More details, quoted from ASP.NET 4.5.1 documentation for appSettings on MSDN:

aspnet:UseTaskFriendlySynchronizationContext

Specifies how asynchronous code paths in ASP.NET 4.5 behave.

...

If this key value is set to false [default], asynchronous code paths in ASP.NET 4.5 behave as they did in ASP.NET 4.0. If this key value is set to true, ASP.NET 4.5 uses code paths that are optimized for Task-returning APIs. Setting this compatibility switch is mandatory for WebSockets-enabled applications, for using Task-based asynchrony in Web Forms pages, and for certain other asynchronous behaviors.

참고URL : https://stackoverflow.com/questions/9562836/whats-the-meaning-of-usetaskfriendlysynchronizationcontext