Table of Contents
Creating a CancellationToken
Passing the Token to Tasks
Requesting Cancellation
Responding to Cancellation in Async Methods
Home Backend Development C#.Net Tutorial How to create and use a CancellationToken in C#?

How to create and use a CancellationToken in C#?

Sep 21, 2025 am 01:49 AM
c#

Create a CancellationTokenSource Gets a CancellationToken, used to notify other threads or components to cancel the operation. 2. Pass the token to an asynchronous method that supports cancellation (such as Task.Run). The task can periodically check the cancellation request to achieve graceful termination.

How to create and use a CancellationToken in C#?

A CancellationToken in C# allows you to signal from one thread or component to an operation running elsewhere that it should stop what it's doing. This is essential for gracefully canceling long-running or asynchronous tasks. Here's how to create and use one properly.

Creating a CancellationToken

The token is typically created through a CancellationTokenSource , which manages the lifecycle of the cancellation request.

  • Create a CancellationTokenSource object.
  • Obtain the token via its Token property.
  • Pass this token to methods that support cancellation.

Example:

 CancellationTokenSource cts = new CancellationTokenSource();<br> CancellationToken token = cts.Token;

Passing the Token to Tasks

Most async methods in .NET (like Task.Run , or methods in HttpClient, Stream, etc.) accept a CancellationToken as a parameter.

  • Pass the token when starting the operation.
  • The operation can periodically check if cancellation has been requested.

Example with Task.Run:

 Task task = Task.Run(() =><br> {<br> for (int i = 0; i < 100; i )<br> {<br> if (token.IsCancellationRequested)<br> {<br> Console.WriteLine("Operation cancelled.");<br> return;<br> }<br> Console.WriteLine($"Working... {i}%");<br> Thread.Sleep(100);<br> }<br> }, token);

Requesting Cancellation

To cancel the operation, call Cancel() on the CancellationTokenSource .

  • This sets the token's IsCancellationRequested to true.
  • It does not force the task to stop — the operation must check the token and respond appropriately.

Example:

 // Cancel after 2 seconds<br> Thread.Sleep(2000);<br> cts.Cancel();

You can also use CancelAfter() to schedule cancellation automatically:

 cts.CancelAfter(2000); // Cancel in 2 seconds

Responding to Cancellation in Async Methods

In async code, throw a OperationCanceledException when cancellation is detected to follow standard patterns.

Example:

 async Task DoWorkAsync(CancellationToken token)<br> {<br> for (int i = 0; i < 100; i )<br> {<br> token.ThrowIfCancellationRequested();<br> await Task.Delay(100, token); // Delay respects token<br> }<br> }

Using ThrowIfCancellationRequested() ensures proper exception handling and integrates well with Task and async/await .

Basically, use CancellationTokenSource to create and trigger cancellation, pass the token to operations, and check it regularly to allow graceful shutdown. It's a cooperative model — the receiving code must participate. That's how it stays safe and predictable.

The above is the detailed content of How to create and use a CancellationToken in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Unity game development: C# implements 3D physics engine and AI behavior tree Unity game development: C# implements 3D physics engine and AI behavior tree May 16, 2025 pm 02:09 PM

In Unity, 3D physics engines and AI behavior trees can be implemented through C#. 1. Use the Rigidbody component and AddForce method to create a scrolling ball. 2. Through behavior tree nodes such as Patrol and ChasePlayer, AI characters can be designed to patrol and chase players.

The Community of C# .NET Developers: Resources and Support The Community of C# .NET Developers: Resources and Support May 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

C# and C  : Exploring the Different Paradigms C# and C : Exploring the Different Paradigms May 08, 2025 am 12:06 AM

The main differences between C# and C are memory management, polymorphism implementation and performance optimization. 1) C# uses a garbage collector to automatically manage memory, while C needs to be managed manually. 2) C# realizes polymorphism through interfaces and virtual methods, and C uses virtual functions and pure virtual functions. 3) The performance optimization of C# depends on structure and parallel programming, while C is implemented through inline functions and multithreading.

How does C# handle exceptions, and what are best practices for try-catch-finally blocks? How does C# handle exceptions, and what are best practices for try-catch-finally blocks? Jun 10, 2025 am 12:15 AM

C# implements a structured exception handling mechanism through try, catch and finally blocks. Developers place possible error code in the try block, catch specific exceptions (such as IOException, SqlException) in the catch block, and perform resource cleaning in the finally block. 1. Specific exceptions should be caught instead of general exceptions (such as Exception) to avoid hiding serious errors and improve debugging efficiency; 2. Avoid over-use try-catch in performance-critical code. It is recommended to check conditions in advance or use methods such as TryParse instead; 3. Always release resources in finally blocks or using statements to ensure that files, connections, etc. are closed correctly.

C# .NET in the Modern World: Applications and Industries C# .NET in the Modern World: Applications and Industries May 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

What is the role of the Common Language Runtime (CLR) in executing C# code? What is the role of the Common Language Runtime (CLR) in executing C# code? Jun 09, 2025 am 12:15 AM

CLR is a runtime engine that executes C# code, responsible for code execution, memory management, security and exception handling. Its workflow is as follows: 1. The C# source code is first compiled into an intermediate language (IL), 2. The runtime CLR converts IL into machine code for a specific platform through instant (JIT) compilation and caches to improve performance; 3. The CLR automatically manages memory, allocates and frees object memory through garbage collector (GC), and supports the use of Finalizers and using statements to process unmanaged resources; 4. CLR forces type safety, validates IL code to prevent common errors, and allows unsafe code blocks when necessary; 5. Exception processing is uniformly managed by CLR, adopts a try-catch-finally structure

What is the difference between Task.Run and Task.Factory.StartNew in C#? What is the difference between Task.Run and Task.Factory.StartNew in C#? Jun 11, 2025 am 12:01 AM

In C#, Task.Run is more suitable for simple asynchronous operations, while Task.Factory.StartNew is suitable for scenarios where task scheduling needs to be finely controlled. Task.Run simplifies the use of background threads, uses thread pools by default and does not capture context, suitable for "sending and forgetting" CPU-intensive tasks; while Task.Factory.StartNew provides more options, such as specifying task schedulers, cancel tokens, and task creation options, which can be used for complex parallel processing or scenarios where custom scheduling is required. The difference in behavior between the two may affect task continuation and subtask behavior, so the appropriate method should be selected according to actual needs.

Developing with C# .NET: A Practical Guide and Examples Developing with C# .NET: A Practical Guide and Examples May 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

See all articles