Last active
August 29, 2015 14:03
-
-
Save Porges/4660dc0e7b5fb8cde5de to your computer and use it in GitHub Desktop.
Open me in LINQPad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Query Kind="Program"> | |
<Namespace>System.Threading.Tasks</Namespace> | |
</Query> | |
void Main() | |
{ | |
Client().Wait(); | |
} | |
async Task Client() | |
{ | |
SynchronizationContext.SetSynchronizationContext(new MySynchronizationContext("Client")); | |
await LibCode(); | |
} | |
async Task LibCode() | |
{ | |
SynchronizationContext.SetSynchronizationContext(new MySynchronizationContext("Library")); | |
await Task.Run(() => { | |
Console.WriteLine("Running some lib code..."); | |
}).ConfigureAwait(false); | |
} | |
// Output: | |
// Running some lib code... | |
// Called back into Client context. | |
// Without ConfigureAwait(false): | |
// Running some lib code... | |
// Called back into Library context. | |
// Called back into Client context. | |
class MySynchronizationContext : SynchronizationContext | |
{ | |
private readonly string _name; | |
public MySynchronizationContext(string name) | |
{ | |
_name = name; | |
} | |
public override void Post(SendOrPostCallback d, object state) | |
{ | |
Console.WriteLine("Called back into " + _name + " context."); | |
base.Post(d, state); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment