编程语言
首页 > 编程语言> > C#-ASP.NET身份文化等待者代码

C#-ASP.NET身份文化等待者代码

作者:互联网

在开发ASP.NET MVC应用程序期间,我遇到了CultureAwaiter,在调用扩展方法WithCurrentCulture时会返回其实例.

我对Microsoft的异步模型比较陌生,因此我很难理解下面标记的四行代码背后的直觉.请注意,我是使用ILSpy从程序集文件版本“ 2.1.30612.0”中获取的…我认为MS尚未提供源供我们查看.

在我假设在同一线程上同步运行的那四行中,看起来变量currentCulture设置为当前线程的区域性(到目前为止非常好).但是,在两行之后,它只接受了该变量并为其设置了当前线程的区域性(即,仅反转了分配).这有什么用?

另一方面,UI文化在这四行中的行为略有不同.注意变量名称中“ UI” /“ Ui”的情况.在这四行代码的第二行,将变量currentUICulture设置为当前线程的UI文化(大概是“记住”它以便以后使用).两行之后,当前线程的UI文化设置为在方法开始时定义的不同变量currentUiCulture(请注意不同的情况).

除了对异步模型的新手了解之外,我至少应该期望CurrentCulture和CurrentUICulture在此方法中具有相同的获取/设置行为.我可能完全错了,但是我的“直觉”感觉告诉我,在这四行中可能发生了错误的分配.

任何人都可以为我的理解提供一些启示吗?可能与ILSpy有关吗?

// Microsoft.AspNet.Identity.TaskExtensions.CultureAwaiter<T>
public void UnsafeOnCompleted(Action continuation)
{
    CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
    CultureInfo currentUiCulture = Thread.CurrentThread.CurrentUICulture;
    this._task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(delegate
    {
        // WHAT'S GOING ON IN THE NEXT FOUR LINES?
        CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
        CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
        Thread.CurrentThread.CurrentCulture = currentCulture;
        Thread.CurrentThread.CurrentUICulture = currentUiCulture;
        try
        {
            continuation();
        }
        finally
        {
            Thread.CurrentThread.CurrentCulture = currentCulture;
            Thread.CurrentThread.CurrentUICulture = currentUICulture;
        }
    });
}

解决方法:

这样做的目的是使用当前区域性设置运行延续,尽管它可能在其他线程上运行.但是我们不想以持久的方式修改该线程的区域性,因为我们不拥有该线程.它是共享的.因此,我们必须在退出之前恢复旧设置.

反编译器可能只是显示误导的变量名. Reflector可以正确执行此操作:

public void UnsafeOnCompleted(Action continuation)
{
    CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
    CultureInfo currentUiCulture = Thread.CurrentThread.CurrentUICulture;
    this._task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(delegate {
        CultureInfo info1 = Thread.CurrentThread.CurrentCulture;
        CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
        Thread.CurrentThread.CurrentCulture = currentCulture;
        Thread.CurrentThread.CurrentUICulture = currentUiCulture;
        try
        {
            continuation();
        }
        finally
        {
            Thread.CurrentThread.CurrentCulture = info1;
            Thread.CurrentThread.CurrentUICulture = currentUICulture;
        }
    });
}

标签:culture,asynchronous,asp-net-identity,c
来源: https://codeday.me/bug/20191120/2047229.html