using System.Threading.Tasks;
using System.Runtime.CompilerServices;
var res = await new C().M();
public async CustomTask<int> M() {
[AsyncMethodBuilder(typeof(CustomTaskMethodBuilder<>))]
public class CustomTask<T>
public T Result => (Exception, Completed) switch
(null, false) => throw new InvalidOperationException($"Task is still running"),
(not null, _) => throw Exception
public Exception Exception { get; private set; }
public bool Completed { get; private set;}
public void Complete(T result)
CompletionCallbacks?.Invoke();
public void Complete(Exception exception)
CompletionCallbacks?.Invoke();
internal Action CompletionCallbacks;
public CustomAwaiter<T> GetAwaiter() => new CustomAwaiter<T>(this);
public struct CustomAwaiter<T> : ICriticalNotifyCompletion
private CustomTask<T> _task;
internal CustomAwaiter(CustomTask<T> task) => _task = task;
public T GetResult() => _task.Result;
public bool IsCompleted => _task.Completed;
public void UnsafeOnCompleted(Action a) => OnCompleted(a);
public void OnCompleted(Action a) => _task.CompletionCallbacks += a;
public struct CustomTaskMethodBuilder<T>
internal IAsyncStateMachine _stateMachine;
public static CustomTaskMethodBuilder<T> Create() => default;
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
=> stateMachine.MoveNext();
public void SetStateMachine(IAsyncStateMachine stateMachine)
=> _stateMachine = stateMachine;
public void SetException(Exception exception) => Task.Complete(exception);
public void SetResult(T result) => Task.Complete(result);
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
TStateMachine stateMachineCopy = stateMachine;
awaiter.OnCompleted(() =>
stateMachineCopy.MoveNext();
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
TStateMachine stateMachineCopy = stateMachine;
awaiter.OnCompleted(() =>
stateMachineCopy.MoveNext();
private CustomTask<T> _task;
public CustomTask<T> Task => _task ??= new CustomTask<T>();