Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active August 29, 2015 14:03
Show Gist options
  • Save Porges/4660dc0e7b5fb8cde5de to your computer and use it in GitHub Desktop.
Save Porges/4660dc0e7b5fb8cde5de to your computer and use it in GitHub Desktop.
Open me in LINQPad
<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