为什么要检查SynchronizationContext是否为null? [英] Why is SynchronizationContext checked for null?

查看:64
本文介绍了为什么要检查SynchronizationContext是否为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

InstallIfNeeded方法,在try块中:

SynchronizationContext currentContext = AsyncOperationManager.SynchronizationContext;
//Make sure we either have no [....] context
//or that we have one of type SynchronizationContext

if (currentContext == null || currentContext.GetType() == typeof(SynchronizationContext))
{
...

因此,首先,调用AsyncOperationManager.SynchronizationContext getter,并检查其返回值是否为null.在这里是否需要检查null?

So first, AsyncOperationManager.SynchronizationContext getter is called, and its return value is checked for null. Is checking for null necessary here?

下面的AsyncOperationManager.SynchronizationContext的代码.它首先检查当前同步上下文是否为null,如果为null,则创建一个新的上下文.因此,很可能这个getter永远不会返回null.

Code of AsyncOperationManager.SynchronizationContext below. It first checks if Current sync context is null, if it is, then a new one is created. So probably this getter never returns a null.

public static SynchronizationContext SynchronizationContext 
{
get 
{
    if (SynchronizationContext.Current == null) 
    {
        SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
    }
    return SynchronizationContext.Current;
}

推荐答案

这里是否需要检查null?

Is checking for null necessary here?

我以前的回答忽略了以下事实:SynchronizationContext.Current实际上将基于线程创建,而不是跨多个线程创建(感谢@PerSerAl指出了这一点).您显然可以在代码中看到它:

My previous answer neglected the fact that SynchronizationContext.Current will in fact be created on a thread basis, and not across multiple threads (thanks to @PerSerAl for pointing that out). You can obviously see it in the code:

// Get the current SynchronizationContext on the current thread
public static SynchronizationContext Current 
{
    get      
    {
        return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ??
               GetThreadLocalContext();
    }
}

实际上,这确实使null检查变得多余,但可以使自己免受将来可能发生的将来任何更改的影响,从而可以围绕SynchronizationContext实现进行编码.

Effectively, this does in-fact make the null check redundant, but does immune itself from any future changes that may happen in the future to code around SynchronizationContext implementation.

这篇关于为什么要检查SynchronizationContext是否为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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