Last active
December 21, 2015 03:18
-
-
Save robdmoore/6240712 to your computer and use it in GitHub Desktop.
Playing with sync context and async
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
using System; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace SyncContext | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
Run(); | |
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); | |
Run(); | |
Console.Read(); | |
} | |
private static void Run() | |
{ | |
Console.WriteLine("=== Start"); | |
OutputSyncContext(); | |
Console.WriteLine("== Wait"); | |
Start().Wait(); | |
Console.WriteLine("== Wait long-running task"); | |
Task.Factory.StartNew(async () => await Start(), TaskCreationOptions.LongRunning).Wait(); | |
} | |
private static async Task Start() | |
{ | |
OutputSyncContext(); | |
var tasks = Enumerable.Range(1, 10).Select(i => Run(i)).ToArray(); | |
await Task.WhenAll(tasks); | |
} | |
private static async Task Run(int i) | |
{ | |
Console.WriteLine("{0}: Before continuation {1}", Thread.CurrentThread.ManagedThreadId, i); | |
await Task.Delay(200); | |
Console.WriteLine("{0}: After continuation {1}", Thread.CurrentThread.ManagedThreadId, i); | |
} | |
private static void OutputSyncContext() | |
{ | |
if (SynchronizationContext.Current == null) | |
Console.WriteLine("No Sync context"); | |
else | |
Console.WriteLine("Sync context hash code: " + SynchronizationContext.Current.GetHashCode()); | |
} | |
} | |
} |
Author
robdmoore
commented
Aug 15, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment