Skip to content

Commit fb3cc1f

Browse files
committed
Guarantee SetResult if Task is completed earlier
1 parent 284107f commit fb3cc1f

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

ComAsyncResult.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,14 @@ public static unsafe nint Alloc(Lock threadLock, Task task)
265265
// Allocate wait handle
266266
resultP->Handle = PInvoke.CreateEvent(nint.Zero, 1, 0, null);
267267

268+
// If the task is completed before the OnCompleted was triggered, then set the result earlier
269+
// and return the pointer.
270+
if (task.IsCompleted || task.IsCanceled || task.IsFaulted)
271+
{
272+
resultP->SetResult(threadLock, task);
273+
return (nint)resultP;
274+
}
275+
268276
// Set the "attach status" callback to the task completion, then return the async result handle
269277
task.GetAwaiter().OnCompleted(() => resultP->SetResult(threadLock, task));
270278
return (nint)resultP;
@@ -289,6 +297,14 @@ public static unsafe nint Alloc<T>(Lock threadLock, Task<T> task)
289297
// Allocate wait handle
290298
resultP->Handle = PInvoke.CreateEvent(nint.Zero, 1, 0, null);
291299

300+
// If the task is completed before the OnCompleted was triggered, then set the result earlier
301+
// and return the pointer.
302+
if (task.IsCompleted || task.IsCanceled || task.IsFaulted)
303+
{
304+
resultP->SetResult(threadLock, task);
305+
return (nint)resultP;
306+
}
307+
292308
// Set the "attach status" callback to the task completion, then return the async result handle
293309
task.GetAwaiter().OnCompleted(() => resultP->SetResult(threadLock, task));
294310
return (nint)resultP;

0 commit comments

Comments
 (0)