Skip to content

Commit 994ced5

Browse files
committed
Use .NET public API to spawn the async method execution
1 parent 2a2cccc commit 994ced5

File tree

1 file changed

+2
-29
lines changed

1 file changed

+2
-29
lines changed

src/DotNext/Runtime/CompilerServices/SpawningTaskMethodBuilder.cs

Lines changed: 2 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System.Runtime.CompilerServices;
22
using System.Runtime.InteropServices;
3-
using System.Threading.Tasks.Sources;
43

54
namespace DotNext.Runtime.CompilerServices;
65

@@ -32,9 +31,8 @@ public struct SpawningAsyncTaskMethodBuilder<TResult>()
3231
public void Start<TStateMachine>(ref TStateMachine stateMachine)
3332
where TStateMachine : IAsyncStateMachine
3433
{
35-
var awaiter = SpawningAsyncTaskMethodBuilder.Awaiter;
34+
var awaiter = System.Threading.Tasks.Task.Yield().GetAwaiter();
3635
builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
37-
SpawningAsyncTaskMethodBuilder.Schedule();
3836
}
3937

4038
/// <summary>
@@ -100,11 +98,6 @@ public void SetException(Exception e)
10098
[StructLayout(LayoutKind.Auto)]
10199
public struct SpawningAsyncTaskMethodBuilder()
102100
{
103-
internal static readonly ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter Awaiter = new ValueTask(new SpecialCallbackDetector(), 0).ConfigureAwait(false).GetAwaiter();
104-
105-
[ThreadStatic]
106-
private static (Action<object?> WorkItem, object? State) capturedArgs;
107-
108101
private AsyncTaskMethodBuilder builder = AsyncTaskMethodBuilder.Create();
109102

110103
/// <summary>
@@ -121,9 +114,8 @@ public struct SpawningAsyncTaskMethodBuilder()
121114
public void Start<TStateMachine>(ref TStateMachine stateMachine)
122115
where TStateMachine : IAsyncStateMachine
123116
{
124-
var awaiter = Awaiter;
117+
var awaiter = Task.Yield().GetAwaiter();
125118
builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
126-
Schedule();
127119
}
128120

129121
/// <summary>
@@ -175,23 +167,4 @@ public void SetException(Exception e)
175167
/// Gets the task representing the builder's asynchronous operation.
176168
/// </summary>
177169
public Task Task => builder.Task;
178-
179-
internal static void Schedule()
180-
{
181-
var (continuation, state) = capturedArgs;
182-
capturedArgs = default;
183-
ThreadPool.UnsafeQueueUserWorkItem(continuation, state, preferLocal: false);
184-
}
185-
186-
private sealed class SpecialCallbackDetector : IValueTaskSource
187-
{
188-
void IValueTaskSource.GetResult(short token)
189-
{
190-
}
191-
192-
ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => ValueTaskSourceStatus.Pending;
193-
194-
void IValueTaskSource.OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
195-
=> capturedArgs = (continuation, state);
196-
}
197170
}

0 commit comments

Comments
 (0)