Что нового
  • Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Best practice with CancellationToken in .Net Core

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
6,375
Баллы
155
In this tutorial we will lean about CancellationToken and how we can use it.

In earlier days, when we had time taking operations like time consuming DB calls, time consuming HTTP calls we had no option to cancel it.

Using a CancellationToken in your applications provides several benefits, particularly in improving responsiveness, resource management, and user experience. Here are some key advantages:

1. Improved Responsiveness
User Experience: Applications that can cancel long-running tasks quickly respond to user actions, such as canceling a file upload or download, leading to a better user experience.
Real-Time Adjustments: Users can adjust their actions (e.g., stopping a search operation) without waiting for the current operation to complete.

2. Resource Management
Efficient Use of Resources: Canceling unnecessary operations prevents waste of CPU, memory, and other resources. This is particularly important for server-side applications where resources are shared among many users.
Database Connections: In database operations, using CancellationToken can free up database connections that would otherwise be held by long-running queries.

3. Scalability
Handling High Load: Applications can handle high loads more gracefully by canceling operations that are no longer needed, thus freeing up resources for new incoming requests.
Concurrency Control: Effective cancellation helps manage concurrent tasks, ensuring that resources are allocated to the most critical operations.

4. Error Handling and Stability
Graceful Shutdown: When an application needs to shut down or restart, CancellationToken allows for a graceful termination of ongoing operations, reducing the risk of data corruption or inconsistent states.
Preventing Deadlocks: By canceling operations that are taking too long, you can reduce the likelihood of deadlocks and other concurrency issues.

5. Timeout Implementation
Automatic Timeout: Implementing timeouts using CancellationTokenSource.CancelAfter can automatically cancel tasks that exceed a specified duration, ensuring that your application remains responsive.

6. Task Coordination
Cooperative Cancellation: CancellationToken allows for cooperative cancellation, where the operation periodically checks the token to see if cancellation is requested, allowing the operation to clean up and terminate gracefully.
Linked Cancellation Tokens: You can link multiple CancellationTokenSource instances together to cancel multiple operations simultaneously, simplifying the coordination of complex tasks.

7. Simplified Code Maintenance
Standard Pattern: Using CancellationToken establishes a standard pattern for task cancellation, making the code easier to understand and maintain.
Consistent Handling: It provides a consistent way to handle cancellations across different parts of your application, from user-initiated cancellations to automatic timeouts and application shutdowns.

Example Use Cases

Web Applications
: Cancel database queries, file uploads/downloads, and API calls that are no longer needed.

Desktop Applications: Allow users to cancel long-running operations like image processing or data analysis.

Mobile Applications: Improve battery life by canceling background operations when they are no longer needed.

Cloud Services: Efficiently manage resources by canceling operations in response to scaling events or maintenance windows.

Here’s a simplified example of how CancellationToken can be used to cancel an ongoing operation:


public async Task LongRunningOperationAsync(CancellationToken cancellationToken)
{
for (int i = 0; i < 100; i++)
{
// Periodically check if cancellation is requested
cancellationToken.ThrowIfCancellationRequested();

// Simulate some work
await Task.Delay(100);
}
}

public async Task MainAsync()
{
using var cts = new CancellationTokenSource();

// Cancel the operation after 2 seconds
cts.CancelAfter(TimeSpan.FromSeconds(2));

try
{
await LongRunningOperationAsync(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was canceled.");
}
}


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх