SpawningAsyncTaskMethodBuilder<TResult>
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;
using System.Threading.Tasks;
namespace DotNext.Runtime.CompilerServices
{
[StructLayout(LayoutKind.Auto)]
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public struct SpawningAsyncTaskMethodBuilder<[System.Runtime.CompilerServices.Nullable(2)] TResult>
{
private AsyncTaskMethodBuilder<TResult> builder;
public Task<TResult> Task => builder.Task;
public SpawningAsyncTaskMethodBuilder()
{
builder = AsyncTaskMethodBuilder<TResult>.Create();
}
[return: System.Runtime.CompilerServices.Nullable(new byte[] {
0,
1
})]
public static SpawningAsyncTaskMethodBuilder<TResult> Create()
{
return new SpawningAsyncTaskMethodBuilder<TResult>();
}
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
AdvanceStateMachineWorkItem awaiter = default(AdvanceStateMachineWorkItem);
this.builder.AwaitOnCompleted(ref awaiter, ref stateMachine);
ThreadPool.UnsafeQueueUserWorkItem(awaiter, false);
}
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
this.builder.AwaitOnCompleted(ref awaiter, ref stateMachine);
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
this.builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
builder.SetStateMachine(stateMachine);
}
[IsReadOnly]
public void SetResult(TResult result)
{
AsyncTaskMethodBuilder<TResult> asyncTaskMethodBuilder = builder;
asyncTaskMethodBuilder.SetResult(result);
}
public void SetException(Exception e)
{
builder.SetException(e);
}
}
}