|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Runtime.CompilerServices; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Microsoft.AspNetCore.Internal; |
| 8 | +using Xunit; |
| 9 | + |
| 10 | +namespace Microsoft.AspNetCore.SignalR.Client.Tests |
| 11 | +{ |
| 12 | + public class TimerAwaitableTests |
| 13 | + { |
| 14 | + [Fact] |
| 15 | + public void FinalizerRunsIfTimerAwaitableReferencesObject() |
| 16 | + { |
| 17 | + var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 18 | + UseTimerAwaitableAndUnref(tcs); |
| 19 | + |
| 20 | + // Make sure it *really* cleans up |
| 21 | + for (int i = 0; i < 5 && !tcs.Task.IsCompleted; i++) |
| 22 | + { |
| 23 | + GC.Collect(); |
| 24 | + GC.WaitForPendingFinalizers(); |
| 25 | + } |
| 26 | + |
| 27 | + // Make sure the finalizer runs |
| 28 | + Assert.True(tcs.Task.IsCompleted); |
| 29 | + } |
| 30 | + |
| 31 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 32 | + private void UseTimerAwaitableAndUnref(TaskCompletionSource<object> tcs) |
| 33 | + { |
| 34 | + _ = new ObjectWithTimerAwaitable(tcs).Start(); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // This object holds onto a TimerAwaitable referencing the callback (the async continuation is the callback) |
| 39 | + // it also has a finalizer that triggers a tcs so callers can be notified when this object is being cleaned up. |
| 40 | + public class ObjectWithTimerAwaitable |
| 41 | + { |
| 42 | + private readonly TimerAwaitable _timer; |
| 43 | + private readonly TaskCompletionSource<object> _tcs; |
| 44 | + private int _count; |
| 45 | + |
| 46 | + public ObjectWithTimerAwaitable(TaskCompletionSource<object> tcs) |
| 47 | + { |
| 48 | + _tcs = tcs; |
| 49 | + _timer = new TimerAwaitable(TimeSpan.Zero, TimeSpan.FromSeconds(1)); |
| 50 | + _timer.Start(); |
| 51 | + } |
| 52 | + |
| 53 | + public async Task Start() |
| 54 | + { |
| 55 | + using (_timer) |
| 56 | + { |
| 57 | + while (await _timer) |
| 58 | + { |
| 59 | + _count++; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + ~ObjectWithTimerAwaitable() |
| 65 | + { |
| 66 | + _tcs.TrySetResult(null); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments