So here is what I see (the first two bits match your question):
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)) {
What then comes:
public static SynchronizationContext SynchronizationContext { get { if (SynchronizationContext.Current == null) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); } return SynchronizationContext.Current; }
Which then leads to: in the line (SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
public static void SetSynchronizationContext(SynchronizationContext syncContext) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.SynchronizationContext = syncContext; ec.SynchronizationContextNoFlow = syncContext; }
But then it returns SynchronizationContext.Current
public static SynchronizationContext Current { get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext(); } }
It could potentially be here.
private static SynchronizationContext GetThreadLocalContext() { SynchronizationContext context = null; #if FEATURE_APPX if (context == null && Environment.IsWinRTSupported) context = GetWinRTContext(); #endif return context; }
As you can see, context can be null if IsWinRTSupported returns false.
Based on what I see, a zero check is probably a good idea. I do not know if the first condition of Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext return null, but taking into account the operator ?? , what is possible.
source share