Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
synccontext_test.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.Generic;
public class Hi
{
public class BatchContext : SynchronizationContext
{
readonly int n = 5;
int count = 0;
List<SendOrPostCallback> batch = new List<SendOrPostCallback>();
public override void Post (SendOrPostCallback d, object state)
{
count++;
Console.WriteLine (count);
d (state);
}
}
static void Main (string[] args)
{
SynchronizationContext.SetSynchronizationContext (new BatchContext ());
var scheduler = TaskScheduler.FromCurrentSynchronizationContext ();
var task = Task.Factory.StartNew (() => run (0), CancellationToken.None, TaskCreationOptions.AttachedToParent, scheduler );
task.ContinueWith ((obj) => boo (), scheduler);
}
static async void run (object o)
{
int y;
var r = new List<int>();
for (int x = 0; x < 5; x++) {
r.Add (await proc (null));
}
y = await proc (1);
Console.WriteLine (y);
Console.WriteLine (r);
}
static async Task<int> proc (object o)
{
var x = new System.Random ().Next();
await Task.Delay (500);
return x;
}
static async Task<int> boo ()
{
Console.WriteLine ("boo");
Thread.Sleep (10000);
return 3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment