ContinueWith loses SynchronizationContext

The following fragment SynchronizationContextis lost, and because of this also CurrentCulture, and CurrentUICulture. Log()derived from this answer .

public async Task<ActionResult> Index()
{
    Log("before GetAsync");
    await new HttpClient().GetAsync("http://www.example.com/")
        .ContinueWith(request =>
        {
            Log("ContinueWith");
            request.Result.EnsureSuccessStatusCode();
        }, TaskContinuationOptions.AttachedToParent);

    return View();
}

static void Log(string message)
{
    var ctx = System.Threading.SynchronizationContext.Current;
    System.Diagnostics.Debug.Print("{0}; thread: {1}, context: {2}, culture: {3}, uiculture: {4}",
        message,
        System.Threading.Thread.CurrentThread.ManagedThreadId,
        ctx != null ? ctx.GetType().Name : String.Empty,
        System.Threading.Thread.CurrentThread.CurrentCulture.Name,
        System.Threading.Thread.CurrentThread.CurrentUICulture.Name);
}

This is the conclusion:

before GetAsync; stream: 56, context: AspNetSynchronizationContext, culture: nl, niculture: nl Continue with; stream: 46, context :, culture: nl-BE, niculture: en-US

Prior GetAsyncculture and culture of the user interface have the meanings set in Application_BeginRequest. There ContinueWithis no context inside , culture is set to the value provided by the browser, and culture is set to the default value for the user interface culture.

From what I understand, everything AspNetSynchronizationContextshould happen automatically. What is wrong with my code?

+2
2

, TaskScheduler, .

public async Task<ActionResult> Index()
{
    Log("before GetAsync");
    await new HttpClient().GetAsync("http://www.example.com/")
        .ContinueWith(request =>
        {
            Log("ContinueWith");
            request.Result.EnsureSuccessStatusCode();
        }, 
        TaskContinuationOptions.AttachedToParent,
        CancellationToken.None,
        TaskScheduler.FromCurrentSynchronizationContext());

    return View();
}

, await, SynchronizationContext. :

public async Task<ActionResult> Index()
    {
        Log("before GetAsync");
        HttpResponseMessage request = await new HttpClient().GetAsync("http://www.example.com/");

        //everything below here is you 'continuation' on the request context
        Log("ContinueWith");
        request.EnsureSuccessStatusCode();

        return View();
    }
+5

TaskContinuationOptions.ExecuteSynchronously? ...

http://msdn.microsoft.com/en-us/library/vstudio/system.threading.tasks.taskcontinuationoptions

", . , , . , , , . ."

-1

All Articles