-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathBunitRenderer.cs
More file actions
733 lines (613 loc) · 21.8 KB
/
BunitRenderer.cs
File metadata and controls
733 lines (613 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
using Microsoft.Extensions.Logging;
using AngleSharp.Dom;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
namespace Bunit.Rendering;
/// <summary>
/// Represents a bUnit <see cref="BunitRenderer"/> used to render Blazor components and fragments during bUnit tests.
/// </summary>
public sealed class BunitRenderer : Renderer
{
private static readonly ConcurrentDictionary<Type, ConstructorInfo> ComponentActivatorCache = new();
private readonly BunitServiceProvider services;
private readonly List<Task> disposalTasks = [];
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")]
private static extern ref bool GetIsBatchInProgressField(Renderer renderer);
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "SetDirectParameters")]
private static extern void CallSetDirectParameters(ComponentState componentState, ParameterView parameters);
private readonly object renderTreeUpdateLock = new();
private readonly HashSet<int> returnedRenderedComponentIds = new();
private readonly List<BunitRootComponent> rootComponents = new();
private readonly ILogger<BunitRenderer> logger;
private bool disposed;
private TaskCompletionSource<Exception> unhandledExceptionTsc = new(TaskCreationOptions.RunContinuationsAsynchronously);
private Exception? capturedUnhandledException;
private bool IsBatchInProgress
{
#pragma warning disable S1144 // Unused private types or members should be removed
get
{
return GetIsBatchInProgressField(this);
}
#pragma warning restore S1144 // Unused private types or members should be removed
set
{
GetIsBatchInProgressField(this) = value;
}
}
/// <summary>
/// Gets a <see cref="Task{Exception}"/>, which completes when an unhandled exception
/// is thrown during the rendering of a component, that is caught by the renderer.
/// </summary>
public Task<Exception> UnhandledException => unhandledExceptionTsc.Task;
/// <inheritdoc/>
public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault();
/// <summary>
/// Gets the number of render cycles that has been performed.
/// </summary>
internal int RenderCount { get; }
#if NET9_0_OR_GREATER
private RendererInfo? rendererInfo;
/// <inheritdoc/>
[SuppressMessage(
"Design",
"CA1065:Do not raise exceptions in unexpected locations",
Justification = "The exception is raised to guide users."
)]
protected override RendererInfo RendererInfo =>
rendererInfo ?? throw new MissingRendererInfoException();
/// <inheritdoc/>
public void SetRendererInfo(RendererInfo? rendererInfo)
{
this.rendererInfo = rendererInfo;
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="BunitRenderer"/> class.
/// </summary>
public BunitRenderer(BunitServiceProvider services, ILoggerFactory loggerFactory)
: base(
services,
loggerFactory,
new BunitComponentActivator(
services,
services.GetRequiredService<ComponentFactoryCollection>(),
externalComponentActivator: null))
{
this.services = services;
logger = loggerFactory.CreateLogger<BunitRenderer>();
ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService<IJSRuntime>());
}
/// <summary>
/// Initializes a new instance of the <see cref="BunitRenderer"/> class.
/// </summary>
public BunitRenderer(BunitServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator)
: base(
services,
loggerFactory,
new BunitComponentActivator(
services,
services.GetRequiredService<ComponentFactoryCollection>(),
componentActivator))
{
this.services = services;
logger = loggerFactory.CreateLogger<BunitRenderer>();
ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService<IJSRuntime>());
}
/// <summary>
/// Renders a <typeparamref name="TComponent"/> with the parameters build with the <paramref name="parameterBuilder"/> passed to it.
/// </summary>
/// <typeparam name = "TComponent" > The type of component to render.</typeparam>
/// <param name="parameterBuilder">The a builder to create parameters to pass to the component.</param>
/// <returns>A <see cref="RenderedComponent{TComponent}"/> that provides access to the rendered component.</returns>
public IRenderedComponent<TComponent> Render<TComponent>(Action<ComponentParameterCollectionBuilder<TComponent>>? parameterBuilder = null)
where TComponent : IComponent
{
var builder = new ComponentParameterCollectionBuilder<TComponent>(parameterBuilder);
var renderFragment = builder.Build().ToRenderFragment<TComponent>();
var renderedComponent = RenderFragment(renderFragment);
return renderedComponent.FindComponent<TComponent>();
}
/// <summary>
/// Renders the <paramref name="renderFragment"/>.
/// </summary>
/// <param name="renderFragment">The <see cref="Microsoft.AspNetCore.Components.RenderFragment"/> to render.</param>
/// <returns>A <see cref="IRenderedComponent{TComponent}"/> that provides access to the rendered <paramref name="renderFragment"/>.</returns>
public IRenderedComponent<IComponent> RenderFragment(RenderFragment renderFragment)
=> Render(renderFragment);
/// <summary>
/// Notifies the renderer that an event has occurred.
/// </summary>
/// <param name="eventHandlerId">The <see cref="RenderTreeFrame.AttributeEventHandlerId"/> value from the original event attribute.</param>
/// <param name="fieldInfo">Information that the renderer can use to update the state of the existing render tree to match the UI.</param>
/// <param name="eventArgs">Arguments to be passed to the event handler.</param>
/// <returns>A <see cref="Task"/> which will complete once all asynchronous processing related to the event has completed.</returns>
public new Task DispatchEventAsync(
ulong eventHandlerId,
EventFieldInfo fieldInfo,
EventArgs eventArgs) => DispatchEventAsync(eventHandlerId, fieldInfo, eventArgs, ignoreUnknownEventHandlers: false);
/// <summary>
/// Notifies the renderer that an event has occurred.
/// </summary>
/// <param name="eventHandlerId">The <see cref="RenderTreeFrame.AttributeEventHandlerId"/> value from the original event attribute.</param>
/// <param name="fieldInfo">Information that the renderer can use to update the state of the existing render tree to match the UI.</param>
/// <param name="eventArgs">Arguments to be passed to the event handler.</param>
/// <param name="ignoreUnknownEventHandlers">Set to true to ignore the <see cref="UnknownEventHandlerIdException"/>.</param>
/// <returns>A <see cref="Task"/> which will complete once all asynchronous processing related to the event has completed.</returns>
public new Task DispatchEventAsync(
ulong eventHandlerId,
EventFieldInfo fieldInfo,
EventArgs eventArgs,
bool ignoreUnknownEventHandlers)
{
ArgumentNullException.ThrowIfNull(fieldInfo);
ObjectDisposedException.ThrowIf(disposed, this);
// Calling base.DispatchEventAsync updates the render tree
// if the event contains associated data.
lock (renderTreeUpdateLock)
{
ObjectDisposedException.ThrowIf(disposed, this);
var result = Dispatcher.InvokeAsync(() =>
{
ResetUnhandledException();
try
{
logger.LogDispatchingEvent(eventHandlerId, fieldInfo, eventArgs);
return base.DispatchEventAsync(eventHandlerId, fieldInfo, eventArgs);
}
catch (ArgumentException ex) when (string.Equals(ex.Message, $"There is no event handler associated with this event. EventId: '{eventHandlerId}'. (Parameter 'eventHandlerId')", StringComparison.Ordinal))
{
if (ignoreUnknownEventHandlers)
{
return Task.CompletedTask;
}
var betterExceptionMsg = new UnknownEventHandlerIdException(eventHandlerId, fieldInfo, ex);
return Task.FromException(betterExceptionMsg);
}
});
if (result.IsFaulted && result.Exception is not null)
{
HandleException(result.Exception);
}
AssertNoUnhandledExceptions();
return result;
}
}
/// <summary>
/// Performs a depth-first search for the first <typeparamref name="TComponent"/> child component of the <paramref name="parentComponent"/>.
/// </summary>
/// <typeparam name="TComponent">Type of component to find.</typeparam>
/// <param name="parentComponent">Parent component to search.</param>
public IRenderedComponent<TComponent> FindComponent<TComponent>(IRenderedComponent<IComponent> parentComponent)
where TComponent : IComponent
{
var foundComponents = FindComponents<TComponent>(parentComponent, 1);
return foundComponents.Count == 1
? foundComponents[0]
: throw new ComponentNotFoundException(typeof(TComponent));
}
/// <summary>
/// Performs a depth-first search for all <typeparamref name="TComponent"/> child components of the <paramref name="parentComponent"/>.
/// </summary>
/// <typeparam name="TComponent">Type of components to find.</typeparam>
/// <param name="parentComponent">Parent component to search.</param>
public IReadOnlyList<IRenderedComponent<TComponent>> FindComponents<TComponent>(IRenderedComponent<IComponent> parentComponent)
where TComponent : IComponent
=> FindComponents<TComponent>(parentComponent, int.MaxValue);
/// <summary>
/// Disposes all components rendered by the <see cref="BunitRenderer" />.
/// </summary>
public Task DisposeComponents()
{
ObjectDisposedException.ThrowIf(disposed, this);
Task? returnTask;
lock (renderTreeUpdateLock)
{
returnTask = Dispatcher.InvokeAsync(async () =>
{
ResetUnhandledException();
foreach (var root in rootComponents)
{
root.Detach();
}
await Task.WhenAll(disposalTasks).ConfigureAwait(false);
disposalTasks.Clear();
});
rootComponents.Clear();
}
return returnTask;
}
/// <inheritdoc/>
protected override ComponentState CreateComponentState(int componentId, IComponent component, ComponentState? parentComponentState)
{
ArgumentNullException.ThrowIfNull(component);
var TComponent = component.GetType();
var renderedComponentType = typeof(RenderedComponent<>).MakeGenericType(TComponent);
var renderedComponent = CreateComponentInstance();
Debug.Assert(renderedComponent is not null);
return (ComponentState)renderedComponent;
object CreateComponentInstance()
{
var constructorInfo = ComponentActivatorCache.GetOrAdd(renderedComponentType, type
=> type.GetConstructor(
[
typeof(BunitRenderer),
typeof(int),
typeof(IComponent),
typeof(IServiceProvider),
typeof(ComponentState)
])!);
Debug.Assert(constructorInfo is not null);
return constructorInfo.Invoke([this, componentId, component, services, parentComponentState]);
}
}
/// <inheritdoc/>
protected override IComponent ResolveComponentForRenderMode(Type componentType, int? parentComponentId,
IComponentActivator componentActivator, IComponentRenderMode renderMode)
{
ArgumentNullException.ThrowIfNull(componentActivator);
return componentActivator.CreateInstance(componentType);
}
#if NET9_0_OR_GREATER
/// <inheritdoc/>
protected override IComponentRenderMode? GetComponentRenderMode(IComponent component)
{
ArgumentNullException.ThrowIfNull(component);
// Search from the current component all the way up the render tree.
// All components must have the same render mode specified (or none at all).
// Return the render mode that is found after checking the full tree.
return GetAndValidateRenderMode(component, childRenderMode: null);
IComponentRenderMode? GetAndValidateRenderMode(
IComponent component,
IComponentRenderMode? childRenderMode
)
{
var componentState = GetComponentState(component);
var renderMode = GetRenderModeForComponent(componentState);
if (
childRenderMode is not null
&& renderMode is not null
&& childRenderMode != renderMode
)
{
throw new RenderModeMisMatchException();
}
return componentState.ParentComponentState is null
? renderMode ?? childRenderMode
: GetAndValidateRenderMode(
componentState.ParentComponentState.Component,
renderMode ?? childRenderMode
);
}
IComponentRenderMode? GetRenderModeForComponent(ComponentState componentState)
{
var renderModeAttribute = componentState.Component
.GetType()
.GetCustomAttribute<RenderModeAttribute>();
if (renderModeAttribute is { Mode: not null })
{
return renderModeAttribute.Mode;
}
if (componentState.ParentComponentState is not null)
{
var parentFrames = GetCurrentRenderTreeFrames(
componentState.ParentComponentState.ComponentId
);
var foundComponentStart = false;
for (var i = 0; i < parentFrames.Count; i++)
{
ref var frame = ref parentFrames.Array[i];
if (frame.FrameType is RenderTreeFrameType.Component)
{
foundComponentStart = frame.ComponentId == componentState.ComponentId;
}
else if (
foundComponentStart
&& frame.FrameType is RenderTreeFrameType.ComponentRenderMode
)
{
return frame.ComponentRenderMode;
}
}
}
return null;
}
}
#endif
/// <inheritdoc/>
protected override void AddPendingTask(ComponentState? componentState, Task task)
{
if (componentState is null)
{
ArgumentNullException.ThrowIfNull(task);
AddDisposalTaskToQueue();
}
base.AddPendingTask(componentState, task);
void AddDisposalTaskToQueue()
{
var t = task;
t = task.ContinueWith(_ =>
{
disposalTasks.Remove(t);
}, TaskScheduler.Current);
disposalTasks.Add(t);
}
}
internal Task SetDirectParametersAsync<TComponent>(IRenderedComponent<TComponent> renderedComponent, ParameterView parameters)
where TComponent : IComponent
{
ObjectDisposedException.ThrowIf(disposed, this);
var result = Dispatcher.InvokeAsync(() =>
{
try
{
IsBatchInProgress = true;
SetDirectParametersViaComponentState(this, renderedComponent.ComponentId, parameters);
}
catch (TargetInvocationException ex) when (ex.InnerException is not null)
{
throw ex.InnerException;
}
finally
{
IsBatchInProgress = false;
}
ProcessPendingRender();
});
if (result.IsFaulted && result.Exception is not null)
{
HandleException(result.Exception);
}
AssertNoUnhandledExceptions();
return result;
static void SetDirectParametersViaComponentState(BunitRenderer renderer, int componentId, in ParameterView parameters)
{
var componentState = renderer.GetComponentState(componentId);
CallSetDirectParameters(componentState, parameters);
}
}
/// <inheritdoc/>
protected override void ProcessPendingRender()
{
if (disposed)
{
logger.LogRenderCycleActiveAfterDispose();
return;
}
// Blocks updates to the renderers internal render tree
// while the render tree is being read elsewhere.
// base.ProcessPendingRender calls UpdateDisplayAsync,
// so there is no need to lock in that method.
lock (renderTreeUpdateLock)
{
if (disposed)
{
logger.LogRenderCycleActiveAfterDispose();
return;
}
base.ProcessPendingRender();
}
}
/// <inheritdoc/>
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch)
{
var disposedComponentIds = new HashSet<int>();
for (var i = 0; i < renderBatch.DisposedComponentIDs.Count; i++)
{
var id = renderBatch.DisposedComponentIDs.Array[i];
disposedComponentIds.Add(id);
returnedRenderedComponentIds.Remove(id);
}
for (var i = 0; i < renderBatch.UpdatedComponents.Count; i++)
{
var diff = renderBatch.UpdatedComponents.Array[i];
if (disposedComponentIds.Contains(diff.ComponentId))
{
continue;
}
var componentState = GetComponentState(diff.ComponentId);
var renderedComponent = (IRenderedComponent)componentState;
if (returnedRenderedComponentIds.Contains(diff.ComponentId))
{
renderedComponent.UpdateState(hasRendered: true, isMarkupGenerationRequired: diff.Edits.Count > 0);
}
else
{
renderedComponent.UpdateState(hasRendered: true, false);
}
UpdateParents(diff.Edits.Count > 0, componentState, in renderBatch);
}
return Task.CompletedTask;
void UpdateParents(bool hasChanges, ComponentState componentState, in RenderBatch renderBatch)
{
var parent = componentState.ParentComponentState;
if (parent is null)
{
return;
}
if (!IsParentComponentAlreadyUpdated(parent.ComponentId, in renderBatch))
{
if (returnedRenderedComponentIds.Contains(parent.ComponentId))
{
((IRenderedComponent)parent).UpdateState(hasRendered: true, isMarkupGenerationRequired: hasChanges);
}
else
{
((IRenderedComponent)parent).UpdateState(hasRendered: true, false);
}
UpdateParents(hasChanges, parent, in renderBatch);
}
}
static bool IsParentComponentAlreadyUpdated(int componentId, in RenderBatch renderBatch)
{
for (var i = 0; i < renderBatch.UpdatedComponents.Count; i++)
{
var diff = renderBatch.UpdatedComponents.Array[i];
if (diff.ComponentId == componentId)
{
return diff.Edits.Count > 0;
}
}
return false;
}
}
/// <inheritdoc/>
internal new ArrayRange<RenderTreeFrame> GetCurrentRenderTreeFrames(int componentId)
=> base.GetCurrentRenderTreeFrames(componentId);
private readonly Dictionary<int, INodeList> boundaryNodesCache = new();
internal INodeList GetBoundaryNodesForComponent(int componentId)
{
if (boundaryNodesCache.TryGetValue(componentId, out var cached))
{
return cached;
}
var htmlParser = services.GetRequiredService<BunitHtmlParser>();
var boundaryHtml = Htmlizer.GetHtmlWithComponentBoundaries(componentId, this);
var nodes = htmlParser.Parse(boundaryHtml);
boundaryNodesCache[componentId] = nodes;
return nodes;
}
internal void InvalidateBoundaryNodesCache(int componentId)
=> boundaryNodesCache.Remove(componentId);
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposed)
return;
lock (renderTreeUpdateLock)
{
if (disposed)
return;
disposed = true;
if (disposing)
{
returnedRenderedComponentIds.Clear();
disposalTasks.Clear();
unhandledExceptionTsc.TrySetCanceled();
}
Dispatcher.InvokeAsync(() => base.Dispose(disposing));
}
}
private IRenderedComponent<BunitRootComponent> Render(RenderFragment renderFragment)
{
ObjectDisposedException.ThrowIf(disposed, this);
var renderTask = Dispatcher.InvokeAsync(() =>
{
ResetUnhandledException();
var root = new BunitRootComponent(renderFragment);
var rootComponentId = AssignRootComponentId(root);
returnedRenderedComponentIds.Add(rootComponentId);
rootComponents.Add(root);
root.Render();
return rootComponentId;
});
int componentId = -1;
if (!renderTask.IsCompleted)
{
logger.LogAsyncInitialRender();
componentId = renderTask.GetAwaiter().GetResult();
}
else
{
componentId = renderTask.Result;
}
var result = GetRenderedComponent<BunitRootComponent>(componentId);
logger.LogInitialRenderCompleted(result.ComponentId);
AssertNoUnhandledExceptions();
return result;
}
private List<IRenderedComponent<TComponent>> FindComponents<TComponent>(IRenderedComponent<IComponent> parentComponent, int resultLimit)
where TComponent : IComponent
{
ArgumentNullException.ThrowIfNull(parentComponent);
ObjectDisposedException.ThrowIf(disposed, this);
var result = resultLimit == int.MaxValue
? new List<IRenderedComponent<TComponent>>()
: new List<IRenderedComponent<TComponent>>(resultLimit);
// Blocks the renderer from changing the render tree
// while this method searches through it.
lock (renderTreeUpdateLock)
{
ObjectDisposedException.ThrowIf(disposed, this);
FindComponentsInRenderTree(parentComponent.ComponentId);
foreach (var rc in result)
{
((IRenderedComponent)rc).UpdateState(hasRendered: false, isMarkupGenerationRequired: true);
}
}
return result;
void FindComponentsInRenderTree(int componentId)
{
var frames = GetCurrentRenderTreeFrames(componentId);
for (var i = 0; i < frames.Count; i++)
{
ref var frame = ref frames.Array[i];
if (frame.FrameType == RenderTreeFrameType.Component)
{
if (frame.Component is TComponent)
{
result.Add(GetRenderedComponent<TComponent>(frame.ComponentId));
if (result.Count == resultLimit)
return;
}
FindComponentsInRenderTree(frame.ComponentId);
if (result.Count == resultLimit)
return;
}
}
}
}
private IRenderedComponent<TComponent> GetRenderedComponent<TComponent>(int componentId)
where TComponent : IComponent
{
var result = GetComponentState(componentId);
returnedRenderedComponentIds.Add(result.ComponentId);
return (IRenderedComponent<TComponent>)result;
}
/// <inheritdoc/>
protected override void HandleException(Exception exception)
{
ArgumentNullException.ThrowIfNull(exception);
if (disposed)
return;
logger.LogUnhandledException(exception);
capturedUnhandledException = exception;
if (!unhandledExceptionTsc.TrySetResult(capturedUnhandledException))
{
unhandledExceptionTsc = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
unhandledExceptionTsc.SetResult(capturedUnhandledException);
}
}
private void ResetUnhandledException()
{
capturedUnhandledException = null;
if (unhandledExceptionTsc.Task.IsCompleted)
unhandledExceptionTsc = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
}
private void AssertNoUnhandledExceptions()
{
// Ensure we are not throwing an exception while a render is ongoing.
// This could lead to the renderer being disposed which could lead to
// tests failing that should not be failing.
lock (renderTreeUpdateLock)
{
if (disposed)
return;
if (capturedUnhandledException is { } unhandled)
{
capturedUnhandledException = null;
if (unhandled is AggregateException { InnerExceptions.Count: 1 } aggregateException)
{
ExceptionDispatchInfo.Capture(aggregateException.InnerExceptions[0]).Throw();
}
else
{
ExceptionDispatchInfo.Capture(unhandled).Throw();
}
}
}
}
}