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.Threading.Tasks; 6 using Xunit; 7 8 namespace System.Threading.Tests 9 { 10 public static class ManualResetEventCancellationTests 11 { 12 [Fact] CancelBeforeWait()13 public static void CancelBeforeWait() 14 { 15 ManualResetEventSlim mres = new ManualResetEventSlim(); 16 CancellationTokenSource cs = new CancellationTokenSource(); 17 cs.Cancel(); 18 CancellationToken ct = cs.Token; 19 20 const int millisec = 100; 21 TimeSpan timeSpan = new TimeSpan(100); 22 23 EnsureOperationCanceledExceptionThrown( 24 () => mres.Wait(ct), ct, "CancelBeforeWait: An OCE should have been thrown."); 25 EnsureOperationCanceledExceptionThrown( 26 () => mres.Wait(millisec, ct), ct, "CancelBeforeWait: An OCE should have been thrown."); 27 EnsureOperationCanceledExceptionThrown( 28 () => mres.Wait(timeSpan, ct), ct, "CancelBeforeWait: An OCE should have been thrown."); 29 mres.Dispose(); 30 } 31 32 [Fact] CancelAfterWait()33 public static void CancelAfterWait() 34 { 35 CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); 36 CancellationToken cancellationToken = cancellationTokenSource.Token; 37 38 ManualResetEventSlim mres = new ManualResetEventSlim(); 39 40 Task.Run( 41 () => 42 { 43 for (int i = 0; i < 400; i++) ; 44 cancellationTokenSource.Cancel(); 45 } 46 ); 47 48 //Now wait.. the wait should abort and an exception should be thrown 49 EnsureOperationCanceledExceptionThrown( 50 () => mres.Wait(cancellationToken), cancellationToken, 51 "CancelBeforeWait: An OCE(null) should have been thrown that references the cancellationToken."); 52 53 // the token should not have any listeners. 54 // currently we don't expose this.. but it was verified manually 55 } 56 EnsureOperationCanceledExceptionThrown(Action action, CancellationToken token, string message)57 private static void EnsureOperationCanceledExceptionThrown(Action action, CancellationToken token, string message) 58 { 59 OperationCanceledException operationCanceledEx = 60 Assert.Throws<OperationCanceledException>(action); 61 Assert.Equal(token, operationCanceledEx.CancellationToken); 62 } 63 } 64 } 65 66