What does 'context' exactly mean in C# async/await code?

折月煮酒 提交于 2019-12-03 10:46:56

If I'm not totally wrong, ConfigureAwait(false); only means that the code which runs after the code you are awaiting, is not required to use the SynchronizationContext from before the await.

SynchronizationContext can be different things as Stephen pointed out. So imagine you are in a web environment and your code after the await relies on HttpContext.Current.Items, this might not work anymore if you set ConfigureAwait(false);

The following code in an MVC controller would throw an exception for example

    public async Task<ActionResult> Index()
    {
        System.Web.HttpContext.Current.Items["test"] = "test";

        var result = await SomethingAsync();

        return View();
    }

    private async Task<object> SomethingAsync()
    {
        await Task.Delay(1000).ConfigureAwait(false);

        // this will throw a nullpointer if ConfigureAwait is set to false
        return System.Web.HttpContext.Current.Items["test"];
    }

Your variable though is simply in the scope of the method and therefor it will be available, basically the method closure/scope, if this makes sense?

As I describe in my async intro blog post, the "context" is:

  • SynchronizationContext.Current, unless it is null, in which case it is
  • TaskScheduler.Current. Note that if there is no current task scheduler, then TaskScheduler.Current is the same as TaskScheduler.Default, which is a thread pool context.

The vast majority of the time, this is either a UI or ASP.NET request context (both types of SynchronizationContext), or else it's the thread pool context. Task scheduler contexts seldomly come into play.

Note that this context is just used to schedule the continuation. It doesn't do anything with marshaling; in your example obj is captured just like it would be if it were referenced from a lambda expression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!