Skip to content

Instantly share code, notes, and snippets.

@in-async
Last active December 27, 2017 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save in-async/1c1ff9600705e3f0f5f10151e44d28c4 to your computer and use it in GitHub Desktop.
Save in-async/1c1ff9600705e3f0f5f10151e44d28c4 to your computer and use it in GitHub Desktop.
C# 7.0 Generalized async return types - Minimum Implementation Code for LinqPad 5
<Query Kind="Program">
<Namespace>System.Runtime.CompilerServices</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
</Query>
static void Main() {
var result = GetValueAsync().Result;
Console.WriteLine(result);
}
public static async MyTask<int> GetValueAsync() {
await Task.Delay(1000);
return 123;
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
public struct MyTask<T> {
private Task<T> _task;
public MyTask(Task<T> task) => _task = task;
public T Result => _task.Result;
}
public struct MyTaskMethodBuilder<T> {
private AsyncTaskMethodBuilder<T> _methodBuilder;
public static MyTaskMethodBuilder<T> Create() =>
new MyTaskMethodBuilder<T> { _methodBuilder = AsyncTaskMethodBuilder<T>.Create() };
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine {
_methodBuilder.Start(ref stateMachine);
}
public void SetStateMachine(IAsyncStateMachine stateMachine) {
_methodBuilder.SetStateMachine(stateMachine);
}
public void SetException(Exception exception) {
_methodBuilder.SetException(exception);
}
public void SetResult(T result) {
_methodBuilder.SetResult(result);
}
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine {
_methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine);
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine {
_methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
}
public MyTask<T> Task => new MyTask<T>(_methodBuilder.Task);
}
}
namespace System.Runtime.CompilerServices {
public sealed class AsyncMethodBuilderAttribute : Attribute {
public AsyncMethodBuilderAttribute(Type builderType) {
BuilderType = builderType;
}
public Type BuilderType { get; }
}
}
class EOF {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment