“上下文"在C#异步/等待代码中到底是什么意思? [英] What does 'context' exactly mean in C# async/await code?

查看:115
本文介绍了“上下文"在C#异步/等待代码中到底是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看一些简单的C#异步/等待代码,其中在awaitConfigureAwait(false)之前和之后都有对象引用(obj)

Lets looks at some simple C# async/await code where I have an object reference (obj) before and after an await with ConfigureAwait(false)

private async Task<SomeObject> AnAsyncLibraryMethod(SomeObject obj)
{
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    obj.Name = "Harry"; // <-- obj here

    // MAIN POINT
    var newSubObj = await FetchOverHttpAsync().ConfigureAwait(false);

    // Continuation here
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    obj.Name = "Sally"; // <-- same obj here
    return obj;
}

public class SomeObject { public string Name; }

ConfigureAwait(false)似乎意味着 将延续性编组回所捕获的原始上下文-好的,但这实际上意味着什么?我已经尝试了上面的代码,并正确地引用了obj IS (即使在不同的线程上恢复).

ConfigureAwait(false) seems to means NOT marshal the continuation back to the original context captured - ok, but what does that really mean? I've tried the code above and obj IS correctly referenced back (even when it resumes on a different thread).

因此,上下文"似乎不是线程的工作内存(即线程本地存储).那么上下文"包含什么呢?因此,

So the "context" doesn't appear to be the thread's working memory (i.e. thread local storage). So what does "context" contain? Therefore, what does it really mean to

将连续性编组回捕获的原始上下文

推荐答案

如果我没有完全错,ConfigureAwait(false);仅表示在您正在等待的代码之后之后运行的代码是不需要在等待之前使用SynchronizationContext.

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可以是不同的东西.因此,想象一下您处于Web环境中,并且等待后的代码依赖于HttpContext.Current.Items,如果设置ConfigureAwait(false);

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

例如,MVC控制器中的以下代码将引发异常

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?

这篇关于“上下文"在C#异步/等待代码中到底是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆