• Home
  • About
  • Contact
  • Privacy
  • Terms
  • DCMA
  • Write For Us / Submit
Tech News, Magazine & Review WordPress Theme 2017
  • Tech
    transfer whatsapp from android to iphone

    How to Transfer WhatsApp from Android to iPhone!

    Understanding the Role of Humidity Chambers in Climate Testing

    Understanding the Role of Humidity Chambers in Climate Testing

    Everything You Get to Know About Movember Beard Memes

    Everything You Get to Know About Movember Beard Memes

    Best Book Recommendation Apps

    11 Best Book Recommendation Apps

    How to quickly divide or Split PDF files

    How to Quickly Divide or Split PDF Files

    Enhance your omnichannel service strategies with data-driven insights.

    Black Market for Fraudulent Ad Accounts Found on Facebook

    Sen. Mark Warner and Sen. Marco Rubio at a hearing.

    Trump’s TikTok ban might have been right after all

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    6 Android Apps for Budget Management

    Twitter, Facebook, Lyft layoffs spark fears of dotcom crash 2.0

  • Gear
    • All
    • Camera
    • Laptop
    • Smartphone
    Latest Smart Home Gadgets for a Connected Life

    Latest Smart Home Gadgets for a Connected Life

    Eco-Friendly Products for Students

    Eco-Friendly Products for Students

    Essential Photography Equipment and Gadgets

    Mastering Your Shots: Essential Photography Equipment and Gadgets

    Level Up Your Game: Must-Have Gaming Gear!

    Level Up Your Game: Must-Have Gaming Gear!

    Pixel Watch in the test

    Google Pixel Watch in the Test

    Top 5 Websites To Buy Camera Lenses At Reasonable Price

    Top 5 Websites To Buy Camera Lenses At Reasonable Price

    Trending Tags

    • Best iPhone 7 deals
    • Apple Watch 2
    • Nintendo Switch
    • CES 2017
    • Playstation 4 Pro
    • iOS 10
    • iPhone 7
    • Sillicon Valley
  • Gaming
    9 Best Alternative Games Like Kahoot

    9 Best Alternative Games Like Kahoot

    The Top 8 Free Bubble Shooter Games for Endless Entertainment

    The Top 8 Free Bubble Shooter Games for Endless Entertainment

    Cloud Gaming Revolution: How Streaming is Changing the Future of Gaming

    Cloud Gaming Revolution: How Streaming is Changing the Future of Gaming

    Level Up Your Game: Must-Have Gaming Gear!

    Level Up Your Game: Must-Have Gaming Gear!

    Game Streaming Platforms: Evolution & Impact on Industry

    Game Streaming Platforms: Evolution & Impact on Industry

    The Rise of Esports Games

    Esports Games: Exploring the Ecosystem, Growth, and Impact

  • Crypto
    transfer whatsapp from android to iphone

    How to Transfer WhatsApp from Android to iPhone!

    Understanding the Role of Humidity Chambers in Climate Testing

    Understanding the Role of Humidity Chambers in Climate Testing

    Everything You Get to Know About Movember Beard Memes

    Everything You Get to Know About Movember Beard Memes

    Best Book Recommendation Apps

    11 Best Book Recommendation Apps

    How to quickly divide or Split PDF files

    How to Quickly Divide or Split PDF Files

    Enhance your omnichannel service strategies with data-driven insights.

    Black Market for Fraudulent Ad Accounts Found on Facebook

    Sen. Mark Warner and Sen. Marco Rubio at a hearing.

    Trump’s TikTok ban might have been right after all

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    6 Android Apps for Budget Management

    Twitter, Facebook, Lyft layoffs spark fears of dotcom crash 2.0

  • Business
    transfer whatsapp from android to iphone

    How to Transfer WhatsApp from Android to iPhone!

    Understanding the Role of Humidity Chambers in Climate Testing

    Understanding the Role of Humidity Chambers in Climate Testing

    Everything You Get to Know About Movember Beard Memes

    Everything You Get to Know About Movember Beard Memes

    Best Book Recommendation Apps

    11 Best Book Recommendation Apps

    How to quickly divide or Split PDF files

    How to Quickly Divide or Split PDF Files

    Enhance your omnichannel service strategies with data-driven insights.

    Black Market for Fraudulent Ad Accounts Found on Facebook

    Sen. Mark Warner and Sen. Marco Rubio at a hearing.

    Trump’s TikTok ban might have been right after all

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    6 Android Apps for Budget Management

    Twitter, Facebook, Lyft layoffs spark fears of dotcom crash 2.0

No Result
View All Result
Geeky Insider
  • Tech
    transfer whatsapp from android to iphone

    How to Transfer WhatsApp from Android to iPhone!

    Understanding the Role of Humidity Chambers in Climate Testing

    Understanding the Role of Humidity Chambers in Climate Testing

    Everything You Get to Know About Movember Beard Memes

    Everything You Get to Know About Movember Beard Memes

    Best Book Recommendation Apps

    11 Best Book Recommendation Apps

    How to quickly divide or Split PDF files

    How to Quickly Divide or Split PDF Files

    Enhance your omnichannel service strategies with data-driven insights.

    Black Market for Fraudulent Ad Accounts Found on Facebook

    Sen. Mark Warner and Sen. Marco Rubio at a hearing.

    Trump’s TikTok ban might have been right after all

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    6 Android Apps for Budget Management

    Twitter, Facebook, Lyft layoffs spark fears of dotcom crash 2.0

  • Gear
    • All
    • Camera
    • Laptop
    • Smartphone
    Latest Smart Home Gadgets for a Connected Life

    Latest Smart Home Gadgets for a Connected Life

    Eco-Friendly Products for Students

    Eco-Friendly Products for Students

    Essential Photography Equipment and Gadgets

    Mastering Your Shots: Essential Photography Equipment and Gadgets

    Level Up Your Game: Must-Have Gaming Gear!

    Level Up Your Game: Must-Have Gaming Gear!

    Pixel Watch in the test

    Google Pixel Watch in the Test

    Top 5 Websites To Buy Camera Lenses At Reasonable Price

    Top 5 Websites To Buy Camera Lenses At Reasonable Price

    Trending Tags

    • Best iPhone 7 deals
    • Apple Watch 2
    • Nintendo Switch
    • CES 2017
    • Playstation 4 Pro
    • iOS 10
    • iPhone 7
    • Sillicon Valley
  • Gaming
    9 Best Alternative Games Like Kahoot

    9 Best Alternative Games Like Kahoot

    The Top 8 Free Bubble Shooter Games for Endless Entertainment

    The Top 8 Free Bubble Shooter Games for Endless Entertainment

    Cloud Gaming Revolution: How Streaming is Changing the Future of Gaming

    Cloud Gaming Revolution: How Streaming is Changing the Future of Gaming

    Level Up Your Game: Must-Have Gaming Gear!

    Level Up Your Game: Must-Have Gaming Gear!

    Game Streaming Platforms: Evolution & Impact on Industry

    Game Streaming Platforms: Evolution & Impact on Industry

    The Rise of Esports Games

    Esports Games: Exploring the Ecosystem, Growth, and Impact

  • Crypto
    transfer whatsapp from android to iphone

    How to Transfer WhatsApp from Android to iPhone!

    Understanding the Role of Humidity Chambers in Climate Testing

    Understanding the Role of Humidity Chambers in Climate Testing

    Everything You Get to Know About Movember Beard Memes

    Everything You Get to Know About Movember Beard Memes

    Best Book Recommendation Apps

    11 Best Book Recommendation Apps

    How to quickly divide or Split PDF files

    How to Quickly Divide or Split PDF Files

    Enhance your omnichannel service strategies with data-driven insights.

    Black Market for Fraudulent Ad Accounts Found on Facebook

    Sen. Mark Warner and Sen. Marco Rubio at a hearing.

    Trump’s TikTok ban might have been right after all

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    6 Android Apps for Budget Management

    Twitter, Facebook, Lyft layoffs spark fears of dotcom crash 2.0

  • Business
    transfer whatsapp from android to iphone

    How to Transfer WhatsApp from Android to iPhone!

    Understanding the Role of Humidity Chambers in Climate Testing

    Understanding the Role of Humidity Chambers in Climate Testing

    Everything You Get to Know About Movember Beard Memes

    Everything You Get to Know About Movember Beard Memes

    Best Book Recommendation Apps

    11 Best Book Recommendation Apps

    How to quickly divide or Split PDF files

    How to Quickly Divide or Split PDF Files

    Enhance your omnichannel service strategies with data-driven insights.

    Black Market for Fraudulent Ad Accounts Found on Facebook

    Sen. Mark Warner and Sen. Marco Rubio at a hearing.

    Trump’s TikTok ban might have been right after all

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    14 Gift Ideas for the Home Chef (2022): Vitamix, Cookbooks, and More

    6 Android Apps for Budget Management

    Twitter, Facebook, Lyft layoffs spark fears of dotcom crash 2.0

Submit
Geeky Insider
No Result
View All Result

How to use cancellation tokens in ASP.NET Core 7

by Staff Writer
October 5, 2022
in How To
Reading Time: 5 mins read
How to use cancellation tokens in ASP.NET Core 7
Share on FacebookShare on Twitter

Although ASP.NET Core 7 is the latest version of Microsoft’s open source web application development framework, it takes advantage of countless significant features from previous versions of .NET. One of these significant features is cancellation tokens, which provide a way of gracefully handling multi-threaded applications.

When working with ASP.NET Core applications, it is good practice to make long running operations (such as a database query or background process) cancelable, either after a certain length of time or upon user request, so that the application can release resources and remain responsive. Here’s where cancellation tokens come into play.

Table of Contents

    • READ ALSO
    • How to Turn Off Autoplay on YouTube
    • How to go through your CV in a job interview
  • Create an ASP.NET Core 7 minimal Web API project in Visual Studio 2022
  • What are cancellation tokens? When should we use them?
  • Long running requests in ASP.NET Core
  • Listening for cancellation requests in ASP.NET Core
  • Create a minimal API handler in ASP.NET Core
  • Use a CancellationToken in a minimal API handler
  • Checking cancellation state in ASP.NET Core

READ ALSO

How to protect yourself from phishing

Phishing: The nasty tricks of the cybercriminals – this is how they protect themselves

July 28, 2023
How to Unsend an Email in Outlook

How to Unsend an Email in Outlook

November 16, 2022

This article discusses cancellation tokens, why they are useful, and how to use them in minimal API handlers in ASP.NET Core. To work with the code examples provided in this article, you should have Visual Studio 2022 Preview installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core 7 minimal Web API project in Visual Studio 2022

First off, let’s create an ASP.NET Core minimal API project in Visual Studio. Following these steps will create a new ASP.NET Core 7 Web API project in Visual Studio 2022 Preview:

  1. Launch the Visual Studio 2022 Preview IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, uncheck the check box that says “Use controllers…” since we’ll be using minimal APIs in this example. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be using any of those features here.
  10. Click Create.

We’ll use this ASP.NET Core 7 Web API project to create minimal API endpoints and work with cancellation tokens.

What are cancellation tokens? When should we use them?

A CancellationToken is a lightweight object created by a CancellationTokenSource instance. When a CancellationTokenSource is canceled, all consumers of CancellationTokens are notified accordingly. Additionally, the IsCancellationRequested property of the cancellation token instance is set to true, indicating that the CancellationTokenSource has been canceled and cancellation of the task has been requested.

You can use a CancellationToken to stop a long running operation when the user cancels a request in the web browser. In other words, using a CancellationToken can help you stop long running requests from using resources when the user has stopped or refreshed the web page.

You can use CancellationTokens to stop async tasks as well. In an async task, cancellation indicates that the task should cease performing its current activity. An async task receives a cancellation token and examines it to see if a cancellation is requested. If so, the current operation should cease immediately.

Long running requests in ASP.NET Core

When working on web applications, you might often make use of long running tasks, i.e., database calls, file handling, etc. When an object creates one or more long running operations, it should pass cancellation tokens to all of those operations. Cancellation tokens should also be passed to other internal operations.

Eventually, the object that created the long running operations may — after a time deadline is reached, or when a user stops a request — propagate a cancellation notification to these cancellation tokens. It should be noted that all long running operations must respect the cancellation request and cancel the long running operations so that resources can be released.

Listening for cancellation requests in ASP.NET Core

You can listen for cancellation requests by polling the value of the CancellationToken.IsCancellationRequested property as shown in the code snippet given below.

while(!cancellationToken.IsCancellationRequested)
{
     //Write your code here to perform some operation
}

Another way to listen for cancellation requests is to call the ThrowIfCancellationRequested method, as shown in the code snippet given below.

while(true)
{
     //Write your code here to perform some operation
     cancellationToken.ThrowIfCancellationRequested();
}

And you can listen for cancellation requests by registering a callback as shown in the following code snippet.

WebClient webClient = new WebClient();   
cancellationToken.Register(() =>
{
    webClient.CancelAsync();
});

Create a minimal API handler in ASP.NET Core

Let’s now simulate a long running request and see how cancellation works. First we’ll try a long running request without cancellation. Write the following piece of code in the Program.cs file.

app.MapGet(“/hello”, async () =>
{
    app.Logger.LogInformation(“Request started at: “+DateTime.Now.ToLongTimeString());
    await Task.Delay(TimeSpan.FromSeconds(5));
    app.Logger.LogInformation(“Request completed at: ” + DateTime.Now.ToLongTimeString());
    return “Success”;
});

When you execute this application and hit the /hello endpoint, you will see that the handler executes in its entirety even if you try to stop the request by refreshing the web browser as shown in Figure 1.

cancellation tokens 01 IDG

Figure 1: Without cancellation, the handler executes in its entirety even if the request is aborted by the user.

Use a CancellationToken in a minimal API handler

The following code listing shows how you can inject a CancellationToken into our endpoint handler and pass this token to the Task.Delay method.

app.MapGet(“/hello”, async (CancellationToken token) =>
{
    app.Logger.LogInformation(“Request started at: ” + DateTime.Now.ToLongTimeString());
    await Task.Delay(TimeSpan.FromSeconds(5), token);
    app.Logger.LogInformation(“Request completed at: ” + DateTime.Now.ToLongTimeString());
    return “Success”;
});

Now when you execute the application and hit the /hello endpoint, refreshing the web browser before the request completes will stop the request. You’ll see from the logs that the request never completes. Instead, a TaskCancelledException will be thrown because the CancellationToken.IsCancellationRequested property will be set to true.

The exception messages will contain the trace information on the aborted request as shown in Figure 2.

cancellation tokens 02 IDG

Figure 2: When cancellation has been used in the handler code, a request that is aborted midway will not complete.

Checking cancellation state in ASP.NET Core

You might often want to know if cancellation has been requested on a cancellation token. You can check the cancellation state by examining the IsCancellationRequested property. The IsCancellationRequested property will be true (i.e., will have a boolean value of true) if cancellation has been requested on the token, false otherwise.

As mentioned above, the CancellationToken.ThrowIfCancellationRequested method will throw an OperationCanceledException if the cancellation token instance has requested cancellation.

The following code snippet illustrates how the IsCancellationRequested property can be used to check if the token has requested cancellation. If the request has been cancelled, an instance of OperationCanceledException is thrown.

if (token.IsCancellationRequested)
{
    app.Logger.LogInformation(“Request has been cancelled..”);
    throw new OperationCanceledException();
}

Using cancellation tokens is a good practice, but it is not always recommended in your controller action methods. If the request modifies the state, you will not want such a request to be cancelled. Cancellation tokens are useful mainly for long running calls that consume significant resources, when stopping the request will not have any side effects.

Finally, for the purposes of this article, we used Task.Delay to simulate a long running operation. In its place, you can substitute any long running calls specific to your application’s requirements such as database calls, network calls, file handling operations, downloading files from the internet, and so on.

Copyright © 2022 IDG Communications, Inc.

Source by www.infoworld.com

Related Posts

transfer whatsapp from android to iphone
Articles

How to Transfer WhatsApp from Android to iPhone!

September 19, 2023
How to prevent phishing attacks
How To

How to Prevent Phishing Attacks: Safeguarding Your Digital Identity

May 14, 2023
How to Activate Iphone With Sim Card
Apple

How to Activate Iphone With Sim Card

March 3, 2023
How to quickly divide or Split PDF files
Apps And Softwares

How to Quickly Divide or Split PDF Files

February 28, 2023

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recommended.

Canadian non-profit gets funding to raise awareness of quantum computing threat

Canadian non-profit gets funding to raise awareness of quantum computing threat

August 18, 2022
Daily Deal: Microsoft Surface Pro 5 (Refurbished)

Daily Deal: Microsoft Surface Pro 5 (Refurbished)

September 11, 2022

Trending.

MicroSD card in hand.

How to Move Apps to SD Card on an Amazon Fire Tablet

October 5, 2022
How to Downgrade Google Chrome to an Older Version

How to Downgrade Google Chrome to an Older Version

September 7, 2022
Google's No Internet Dino game running on a laptop computer

How to Hack the Hidden Google Chrome Dinosaur Game

October 23, 2022
Employee Payroll Management Software Simplifying Processes

Employee Payroll Management Software: Simplifying Processes

August 23, 2023
Symbolic Link Header Image. A Windows folder on a blue background.

The Complete Guide to Creating Symbolic Links (aka Symlinks) on Windows

July 27, 2022
Geeky Insider

Geeky Insider is Web based independent Tech Magazine covering Topics Related to Technology, Gadgets, Software, Gaming, Crypto, Business And So on. Read More...

Submit a Techy Post | Write For Us

Feel free to contact us for submission queries. via contact form or email us at [email protected].

Categories

  • Android
  • Apple
  • Apps And Softwares
  • Articles
  • Business
  • Camera
  • Crypto
  • Education
  • Entertainment
  • Gadget and Gear
  • Gaming
  • How To
  • Laptop
  • Marketing
  • Microsoft
  • Review
  • Security
  • Smartphone
  • Technology
00-samsung FRP unlock tool

Unlock Samsung in Minutes: 5 Proven Hacks with the Ultimate FRP Unlock Tool!

September 19, 2023
transfer whatsapp from android to iphone

How to Transfer WhatsApp from Android to iPhone!

September 19, 2023
Understanding the Role of Humidity Chambers in Climate Testing

Understanding the Role of Humidity Chambers in Climate Testing

September 4, 2023
  • Home
  • About
  • Contact
  • Privacy
  • Terms
  • DCMA
  • Write For Us / Submit

© 2022 GeekyInsider.com

No Result
View All Result
  • Home
  • Review
  • Apple
  • Gaming
  • Gadget and Gear
    • Camera
    • Smartphone
  • Microsoft
  • Security