Skip to content

Commit c933b80

Browse files
committed
Rewrite async state machine to avoid throwing exceptions
1 parent 780403b commit c933b80

3 files changed

Lines changed: 272 additions & 7 deletions

File tree

‎src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`2.cs‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -230,13 +230,22 @@ void AddItemsToBatch(IEnumerable<TItem> items)
230230
if (nextBatch.IsEmpty)
231231
return default;
232232

233-
return await _processBatchAsync(nextBatch, batchCancellationToken).ConfigureAwait(false);
234-
}
235-
catch (OperationCanceledException) when (!_entireQueueCancellationToken.IsCancellationRequested)
236-
{
237-
// Don't bubble up cancellation to the queue for the nested batch cancellation. Just because we decided
238-
// to cancel this batch isn't something that should stop processing further batches.
239-
return default;
233+
var (status, exception, result) = await _processBatchAsync(nextBatch, batchCancellationToken).NoThrowAwaitableInternal(false);
234+
if (status == TaskStatus.RanToCompletion)
235+
{
236+
return result;
237+
}
238+
else if (status == TaskStatus.Canceled && !_entireQueueCancellationToken.IsCancellationRequested)
239+
{
240+
// Don't bubble up cancellation to the queue for the nested batch cancellation. Just because we decided
241+
// to cancel this batch isn't something that should stop processing further batches.
242+
return default;
243+
}
244+
else
245+
{
246+
exception!.Throw();
247+
throw ExceptionUtilities.Unreachable();
248+
}
240249
}
241250
catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, ErrorSeverity.Critical))
242251
{

‎src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@
466466
<Compile Include="$(MSBuildThisFileDirectory)System.Text\Utf16Utility.cs" />
467467
<Compile Include="$(MSBuildThisFileDirectory)TestHooks\IExpeditableDelaySource.cs" />
468468
<Compile Include="$(MSBuildThisFileDirectory)TestHooks\TaskExtensions.cs" />
469+
<Compile Include="$(MSBuildThisFileDirectory)TestHooks\ValueTaskExtensions.cs" />
469470
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AbstractSpeculationAnalyzer.cs" />
470471
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AliasSymbolCache.cs" />
471472
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AnnotationTable.cs" />
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System;
6+
using System.Runtime.CompilerServices;
7+
using System.Runtime.ExceptionServices;
8+
using System.Threading.Tasks;
9+
using Roslyn.Utilities;
10+
11+
namespace Microsoft.CodeAnalysis.Shared.TestHooks
12+
{
13+
internal static class ValueTaskExtensions
14+
{
15+
/// <summary>
16+
/// Returns an awaitable for the specified task that will never throw, even if the source task
17+
/// faults or is canceled.
18+
/// </summary>
19+
/// <param name="task">The task whose completion should signal the completion of the returned awaitable.</param>
20+
/// <param name="captureContext">if set to <c>true</c> the continuation will be scheduled on the caller's context; <c>false</c> to always execute the continuation on the threadpool.</param>
21+
/// <returns>An awaitable.</returns>
22+
public static NoThrowValueTaskAwaitable NoThrowAwaitableInternal(this ValueTask task, bool captureContext = true)
23+
{
24+
return new NoThrowValueTaskAwaitable(task, captureContext);
25+
}
26+
27+
/// <summary>
28+
/// Returns an awaitable for the specified task that will never throw, even if the source task
29+
/// faults or is canceled.
30+
/// </summary>
31+
/// <param name="task">The task whose completion should signal the completion of the returned awaitable.</param>
32+
/// <param name="captureContext">if set to <c>true</c> the continuation will be scheduled on the caller's context; <c>false</c> to always execute the continuation on the threadpool.</param>
33+
/// <returns>An awaitable.</returns>
34+
public static NoThrowValueTaskAwaitable<TResult> NoThrowAwaitableInternal<TResult>(this ValueTask<TResult> task, bool captureContext = true)
35+
{
36+
return new NoThrowValueTaskAwaitable<TResult>(task, captureContext);
37+
}
38+
39+
/// <summary>
40+
/// An awaitable that wraps a task and never throws an exception when waited on.
41+
/// </summary>
42+
public readonly struct NoThrowValueTaskAwaitable
43+
{
44+
/// <summary>
45+
/// The task.
46+
/// </summary>
47+
private readonly ValueTask _task;
48+
49+
/// <summary>
50+
/// A value indicating whether the continuation should be scheduled on the current sync context.
51+
/// </summary>
52+
private readonly bool _captureContext;
53+
54+
/// <summary>
55+
/// Initializes a new instance of the <see cref="NoThrowValueTaskAwaitable" /> struct.
56+
/// </summary>
57+
/// <param name="task">The task.</param>
58+
/// <param name="captureContext">Whether the continuation should be scheduled on the current sync context.</param>
59+
public NoThrowValueTaskAwaitable(ValueTask task, bool captureContext)
60+
{
61+
Contract.ThrowIfNull(task, nameof(task));
62+
_task = task;
63+
_captureContext = captureContext;
64+
}
65+
66+
/// <summary>
67+
/// Gets the awaiter.
68+
/// </summary>
69+
/// <returns>The awaiter.</returns>
70+
public NoThrowValueTaskAwaiter GetAwaiter()
71+
{
72+
return new NoThrowValueTaskAwaiter(_task, _captureContext);
73+
}
74+
}
75+
76+
/// <summary>
77+
/// An awaiter that wraps a task and never throws an exception when waited on.
78+
/// </summary>
79+
public readonly struct NoThrowValueTaskAwaiter : ICriticalNotifyCompletion
80+
{
81+
/// <summary>
82+
/// The task.
83+
/// </summary>
84+
private readonly ValueTask _task;
85+
86+
/// <summary>
87+
/// A value indicating whether the continuation should be scheduled on the current sync context.
88+
/// </summary>
89+
private readonly bool _captureContext;
90+
91+
/// <summary>
92+
/// Initializes a new instance of the <see cref="NoThrowValueTaskAwaiter"/> struct.
93+
/// </summary>
94+
/// <param name="task">The task.</param>
95+
/// <param name="captureContext">if set to <c>true</c> [capture context].</param>
96+
public NoThrowValueTaskAwaiter(ValueTask task, bool captureContext)
97+
{
98+
Contract.ThrowIfNull(task, nameof(task));
99+
_task = task;
100+
_captureContext = captureContext;
101+
}
102+
103+
/// <summary>
104+
/// Gets a value indicating whether the task has completed.
105+
/// </summary>
106+
public bool IsCompleted
107+
{
108+
get { return _task.IsCompleted; }
109+
}
110+
111+
/// <summary>
112+
/// Schedules a delegate for execution at the conclusion of a task's execution.
113+
/// </summary>
114+
/// <param name="continuation">The action.</param>
115+
public void OnCompleted(Action continuation)
116+
{
117+
_task.ConfigureAwait(_captureContext).GetAwaiter().OnCompleted(continuation);
118+
}
119+
120+
/// <summary>
121+
/// Schedules a delegate for execution at the conclusion of a task's execution
122+
/// without capturing the ExecutionContext.
123+
/// </summary>
124+
/// <param name="continuation">The action.</param>
125+
public void UnsafeOnCompleted(Action continuation)
126+
{
127+
_task.ConfigureAwait(_captureContext).GetAwaiter().UnsafeOnCompleted(continuation);
128+
}
129+
130+
/// <summary>
131+
/// Does nothing.
132+
/// </summary>
133+
public (TaskStatus Status, ExceptionDispatchInfo? Exception) GetResult()
134+
{
135+
var preserved = _task.Preserve();
136+
if (preserved.IsCompletedSuccessfully)
137+
return (TaskStatus.RanToCompletion, null);
138+
else if (preserved.IsCanceled)
139+
return (TaskStatus.Canceled, ExceptionDispatchInfo.Capture(preserved.AsTask().Exception!.InnerException!));
140+
else if (preserved.IsFaulted)
141+
return (TaskStatus.Faulted, ExceptionDispatchInfo.Capture(preserved.AsTask().Exception!.InnerException!));
142+
else
143+
throw new InvalidOperationException($"Cannot call {nameof(GetResult)} prior to completion.");
144+
}
145+
}
146+
147+
/// <summary>
148+
/// An awaitable that wraps a task and never throws an exception when waited on.
149+
/// </summary>
150+
public readonly struct NoThrowValueTaskAwaitable<TResult>
151+
{
152+
/// <summary>
153+
/// The task.
154+
/// </summary>
155+
private readonly ValueTask<TResult> _task;
156+
157+
/// <summary>
158+
/// A value indicating whether the continuation should be scheduled on the current sync context.
159+
/// </summary>
160+
private readonly bool _captureContext;
161+
162+
/// <summary>
163+
/// Initializes a new instance of the <see cref="NoThrowValueTaskAwaitable{TResult}" /> struct.
164+
/// </summary>
165+
/// <param name="task">The task.</param>
166+
/// <param name="captureContext">Whether the continuation should be scheduled on the current sync context.</param>
167+
public NoThrowValueTaskAwaitable(ValueTask<TResult> task, bool captureContext)
168+
{
169+
Contract.ThrowIfNull(task, nameof(task));
170+
_task = task;
171+
_captureContext = captureContext;
172+
}
173+
174+
/// <summary>
175+
/// Gets the awaiter.
176+
/// </summary>
177+
/// <returns>The awaiter.</returns>
178+
public NoThrowValueTaskAwaiter<TResult> GetAwaiter()
179+
{
180+
return new NoThrowValueTaskAwaiter<TResult>(_task, _captureContext);
181+
}
182+
}
183+
184+
/// <summary>
185+
/// An awaiter that wraps a task and never throws an exception when waited on.
186+
/// </summary>
187+
public readonly struct NoThrowValueTaskAwaiter<TResult> : ICriticalNotifyCompletion
188+
{
189+
/// <summary>
190+
/// The task.
191+
/// </summary>
192+
private readonly ValueTask<TResult> _task;
193+
194+
/// <summary>
195+
/// A value indicating whether the continuation should be scheduled on the current sync context.
196+
/// </summary>
197+
private readonly bool _captureContext;
198+
199+
/// <summary>
200+
/// Initializes a new instance of the <see cref="NoThrowValueTaskAwaiter{TResult}"/> struct.
201+
/// </summary>
202+
/// <param name="task">The task.</param>
203+
/// <param name="captureContext">if set to <c>true</c> [capture context].</param>
204+
public NoThrowValueTaskAwaiter(ValueTask<TResult> task, bool captureContext)
205+
{
206+
Contract.ThrowIfNull(task, nameof(task));
207+
_task = task;
208+
_captureContext = captureContext;
209+
}
210+
211+
/// <summary>
212+
/// Gets a value indicating whether the task has completed.
213+
/// </summary>
214+
public bool IsCompleted
215+
{
216+
get { return _task.IsCompleted; }
217+
}
218+
219+
/// <summary>
220+
/// Schedules a delegate for execution at the conclusion of a task's execution.
221+
/// </summary>
222+
/// <param name="continuation">The action.</param>
223+
public void OnCompleted(Action continuation)
224+
{
225+
_task.ConfigureAwait(_captureContext).GetAwaiter().OnCompleted(continuation);
226+
}
227+
228+
/// <summary>
229+
/// Schedules a delegate for execution at the conclusion of a task's execution
230+
/// without capturing the ExecutionContext.
231+
/// </summary>
232+
/// <param name="continuation">The action.</param>
233+
public void UnsafeOnCompleted(Action continuation)
234+
{
235+
_task.ConfigureAwait(_captureContext).GetAwaiter().UnsafeOnCompleted(continuation);
236+
}
237+
238+
/// <summary>
239+
/// Does nothing.
240+
/// </summary>
241+
public (TaskStatus Status, ExceptionDispatchInfo? Exception, TResult? Result) GetResult()
242+
{
243+
var preserved = _task.Preserve();
244+
if (preserved.IsCompletedSuccessfully)
245+
return (TaskStatus.RanToCompletion, null, preserved.Result);
246+
else if (preserved.IsCanceled)
247+
return (TaskStatus.Canceled, ExceptionDispatchInfo.Capture(preserved.AsTask().Exception!.InnerException!), default);
248+
else if (preserved.IsFaulted)
249+
return (TaskStatus.Faulted, ExceptionDispatchInfo.Capture(preserved.AsTask().Exception!.InnerException!), default);
250+
else
251+
throw new InvalidOperationException($"Cannot call {nameof(GetResult)} prior to completion.");
252+
}
253+
}
254+
}
255+
}

0 commit comments

Comments
 (0)