CSharp · Console
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.CompilerServices;
public class Program
{
public static void Main()
{
Print("Starting");
CurrentThreadSynchronizationContext.Run(async () =>
{
var scheduler = new StopwatchScheduler(
TaskScheduler.FromCurrentSynchronizationContext());
var stopwatch = Stopwatch.StartNew();
await Task.Factory.StartNew(async () =>
{
for (int i = 1; i <= 5; i++)
{
Print("Processing #{0} ({1})", i, TaskScheduler.Current.GetType().Name);
Thread.Sleep(500); // CPU-bound
//await Task.Delay(500); // I/O-bound
await Task.Delay(500).ConfigureAwait(
ConfigureAwaitBehavior.OnlyCaptureTaskScheduler); // I/O-bound
}
}, CancellationToken.None, TaskCreationOptions.None, scheduler).Unwrap();
Print("Total work: {0:#,0} msec", stopwatch.ElapsedMilliseconds);
Print("CPU-bound work: {0:#,0} msec", scheduler.Elapsed.TotalMilliseconds);
});
}
public static void Print(string line, params object[] args)
{
Console.WriteLine("{0:HH:mm:ss.fff} [{1}] > " + String.Format(line, args),
DateTime.Now, Thread.CurrentThread.ManagedThreadId);
}
}
public class StopwatchScheduler : TaskScheduler
{
private readonly TaskScheduler _parentScheduler;
private long _ticks;
public TimeSpan Elapsed { get { return TimeSpan.FromMilliseconds(Volatile.Read(ref _ticks)); } }
public StopwatchScheduler(TaskScheduler parent) { _parentScheduler = parent; }
protected override void QueueTask(Task task)
{
Task.Factory.StartNew(() =>
{
var t0 = Environment.TickCount;
try { this.TryExecuteTask(task); }
finally { Interlocked.Add(ref _ticks, Environment.TickCount - t0); }
}, CancellationToken.None, TaskCreationOptions.None, _parentScheduler);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
protected override IEnumerable<Task> GetScheduledTasks() { yield break; }
}
public class CurrentThreadSynchronizationContext : SynchronizationContext
{
private readonly BlockingCollection<ValueTuple<SendOrPostCallback, object>> _queue
= new BlockingCollection<ValueTuple<SendOrPostCallback, object>>();
public static void Run(Func<Task> action)
{
var context = new CurrentThreadSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(context);
var task = action();
task.ContinueWith(_ => context._queue.CompleteAdding(), TaskScheduler.Default);
foreach (var entry in context._queue.GetConsumingEnumerable()) entry.Item1(entry.Item2);
task.GetAwaiter().GetResult();
SynchronizationContext.SetSynchronizationContext(null);
}
public override void Post(SendOrPostCallback d, object state)
{
_queue.Add(ValueTuple.Create(d, state));
}
}
[Flags]
public enum ConfigureAwaitBehavior
{
NoCapturedContext = 0x1, // equivalent to ConfigureAwait(false)
NoThrow = 0x2, // when set, no exceptions will be thrown for Faulted/Canceled
Asynchronous = 0x4, // force the continuation to be asynchronous
OnlyCaptureTaskScheduler = 0x8, // ignore the synchronization context
}
public static class TaskExtensions2
{
public static ConfiguredTaskAwaitable2 ConfigureAwait(this Task task,
ConfigureAwaitBehavior behavior)
{
if (behavior == ConfigureAwaitBehavior.OnlyCaptureTaskScheduler)
return new ConfiguredTaskAwaitable2(task);
throw new NotImplementedException(behavior.ToString());
}
}
public class ConfiguredTaskAwaitable2 : INotifyCompletion
{
private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter _taskAwaiter;
private readonly TaskScheduler _capturedScheduler;
public ConfiguredTaskAwaitable2(Task task)
{
_taskAwaiter = task.ConfigureAwait(false).GetAwaiter();
_capturedScheduler = TaskScheduler.Current;
}
public ConfiguredTaskAwaitable2 GetAwaiter() { return this; }
public bool IsCompleted { get { return _taskAwaiter.IsCompleted; } }
public void GetResult() { _taskAwaiter.GetResult(); }
public void OnCompleted(Action continuation)
{
_taskAwaiter.OnCompleted(() =>
{
Task.Factory.StartNew(continuation, CancellationToken.None,
TaskCreationOptions.None, _capturedScheduler);
});
}
}