CSharp · Console
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
static class Program
{
static async Task Main()
{
var testTask = Test();
await Task.Delay(1000);
Console.WriteLine("Exception was captured by async state machine");
await testTask;
}
static async Task Test()
{
await new YieldThreadPoolAwaiter();
throw new ApplicationException("Oops!");
}
public struct YieldThreadPoolAwaiter : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
ThreadPool.QueueUserWorkItem(RunAction, continuation);
}
public void GetResult() { }
private static void RunAction(object state)
{
((Action)state)();
}
public bool IsCompleted
{
get { return false; }
}
public YieldThreadPoolAwaiter GetAwaiter() => this;
}
}