I\'m finally looking into the async & await keywords, which I kind of "get", but all the examples I\'ve seen call async methods in the .Net framework, e.g. thi
... how I would write my own "awaitable" method.
Returning a Task is not the only way. You have an option to create a custom awaiter (by implementing GetAwaiter and INotifyCompletion), here is a great read: "Await anything". Examples of .NET APIs returning custom awaiters: Task.Yield(), Dispatcher.InvokeAsync.
I have some posts with custom awaiters here and here, e.g:
// don't use this in production
public static class SwitchContext
{
public static Awaiter Yield() { return new Awaiter(); }
public struct Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public Awaiter GetAwaiter() { return this; }
public bool IsCompleted { get { return false; } }
public void OnCompleted(Action continuation)
{
ThreadPool.QueueUserWorkItem((state) => ((Action)state)(), continuation);
}
public void GetResult() { }
}
}
// ...
await SwitchContext.Yield();