Trace.WriteLine( "_: " + Thread.CurrentThread.ManagedThreadId + " " + (SynchronizationContext.Current != null) );
await new NullSynchronizationContextAwaiter();
Trace.WriteLine( "A: " + Thread.CurrentThread.ManagedThreadId + " " + (SynchronizationContext.Current != null) );
await Task.Delay( 1000 );
Trace.WriteLine( "B: " + Thread.CurrentThread.ManagedThreadId + " " + (SynchronizationContext.Current != null) );
await Task.Delay( 1000 );
Trace.WriteLine( "C: " + Thread.CurrentThread.ManagedThreadId + " " + (SynchronizationContext.Current != null) );
public struct NullSynchronizationContextAwaiter : INotifyCompletion {
private bool IsRequired => SynchronizationContext.Current != null;
public bool IsCompleted => !IsRequired;
public NullSynchronizationContextAwaiter GetAwaiter() {
return this;
}
public void OnCompleted(Action continuation) {
var prev = SynchronizationContext.Current;
Trace.WriteLine( "{" );
SynchronizationContext.SetSynchronizationContext( null );
try {
continuation();
} finally {
SynchronizationContext.SetSynchronizationContext( prev );
Trace.WriteLine( "}" );
}
}
public void GetResult() {
}
}
_: 1 True
{
A: 1 False
}
B: 4 False
C: 4 False