Patterns & Practices for efficiently handling C# async/await cancel processing and timeouts

CreateLinkedTokenSource Pattern

The simplest pattern for cancellation processing is to provide a CancellationToken at the end of the argument and propagate it to the inner methods. If propagated properly, the innermost process will properly handle the CancellationToken and throw an OperationCanceledException when it detects a cancellation.

Make to the Zero Allocation

In most cases, the above pattern is perfectly fine, but you may be concerned about creating a new CancellationTokenSource with CreateLinkedTokenSource each time. Either way, if the async method is executed asynchronously, the asynchronous state machine itself will be allocated, so it is not something to be concerned about. However, if you have an asynchronous implementation that avoids allocation, using IValueTaskSource or PoolingAsyncValueTaskMethodBuilder, it becomes a matter of concern. Also, although it is not a big deal for the frequency of HTTP/1 REST calls, you may want to pay attention to this issue if, for example, the server is exposed to a large amount of parallel execution and the client communicates in every frame in real-time communication.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yoshifumi Kawai

Yoshifumi Kawai

a.k.a. neuecc. Creator of UniRx, UniTask, MessagePack for C#, MagicOnion etc. Microsoft MVP for C#. CEO/CTO of Cysharp Inc. Live and work in Tokyo, Japan.