Permalink
Fetching contributors…
Cannot retrieve contributors at this time
39 lines (32 sloc) 2.64 KB
title ms.custom ms.date ms.prod ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic helpviewer_keywords ms.assetid caps.latest.revision author ms.author manager
How to: Listen for Cancellation Requests That Have Wait Handles
03/30/2017
.net
dotnet-standard
article
cancellation, waiting with wait handles
6e2aa49b-fc84-4bcf-962b-17db98b7edcb
9
rpetrusha
ronpet
wpickett

How to: Listen for Cancellation Requests That Have Wait Handles

If a method is blocked while it is waiting for an event to be signaled, it cannot check the value of the cancellation token and respond in a timely manner. The first example shows how to solve this problem when you are working with events such as xref:System.Threading.ManualResetEvent?displayProperty=nameWithType that do not natively support the unified cancellation framework. The second example shows a more streamlined approach that uses xref:System.Threading.ManualResetEventSlim?displayProperty=nameWithType, which does support unified cancellation.

[!NOTE] When "Just My Code" is enabled, Visual Studio in some cases will break on the line that throws the exception and display an error message that says "exception not handled by user code." This error is benign. You can press F5 to continue from it, and see the exception-handling behavior that is demonstrated in the examples below. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.

Example

The following example uses a xref:System.Threading.ManualResetEvent to demonstrate how to unblock wait handles that do not support unified cancellation.

[!code-csharpCancellation#9] [!code-vbCancellation#9]

Example

The following example uses a xref:System.Threading.ManualResetEventSlim to demonstrate how to unblock coordination primitives that do support unified cancellation. The same approach can be used with other lightweight coordination primitives, such as xref:System.Threading.SemaphoreSlim and xref:System.Threading.CountdownEvent.

[!code-csharpCancellation#10] [!code-vbCancellation#10]

See Also

Cancellation in Managed Threads