SpawningAsyncTaskMethodBuilder
When applied to async method using AsyncMethodBuilderAttribute attribute,
spawns method execution as a new work item in the thread pool, i.e. in parallel.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace DotNext.Runtime.CompilerServices
{
[StructLayout(LayoutKind.Auto)]
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public struct SpawningAsyncTaskMethodBuilder
{
private sealed class StateMachineContainer<TStateMachine> : SpawningAsyncTaskMethodBuilderCore<AsyncTaskMethodBuilder>.StateMachineContainer<TStateMachine> where TStateMachine : IAsyncStateMachine
{
protected override bool IsCompleted => Builder.Task.IsCompleted;
public StateMachineContainer()
{
GC.KeepAlive(Builder.Task);
}
}
private SpawningAsyncTaskMethodBuilderCore<AsyncTaskMethodBuilder> core;
public Task Task {
[IsReadOnly]
get {
return core.Builder.Task;
}
}
public static SpawningAsyncTaskMethodBuilder Create()
{
return default(SpawningAsyncTaskMethodBuilder);
}
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
core.Start<TStateMachine, StateMachineContainer<TStateMachine>>(ref stateMachine);
}
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
core.AwaitOnCompleted<TAwaiter, TStateMachine, StateMachineContainer<TStateMachine>>(ref awaiter, ref stateMachine);
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
core.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine, StateMachineContainer<TStateMachine>>(ref awaiter, ref stateMachine);
}
[IsReadOnly]
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
[IsReadOnly]
public void SetResult()
{
core.Builder.SetResult();
}
[IsReadOnly]
public void SetException(Exception e)
{
core.Builder.SetException(e);
}
}
}