Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The C# Workshop

You're reading from   The C# Workshop Kickstart your career as a software developer with C#

Arrow left icon
Product type Paperback
Published in Sep 2022
Publisher Packt
ISBN-13 9781800566491
Length 780 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Almantas Karpavicius Almantas Karpavicius
Author Profile Icon Almantas Karpavicius
Almantas Karpavicius
Jason Hales Jason Hales
Author Profile Icon Jason Hales
Jason Hales
Mateus Viegas Mateus Viegas
Author Profile Icon Mateus Viegas
Mateus Viegas
Arrow right icon
View More author details
Toc

Running Asynchronous Code Using Tasks

The Task class is used to execute blocks of code asynchronously. Its usage has been somewhat superseded by the newer async and await keywords, but this section will cover the basics of creating tasks as they tend to be pervasive in larger or mature C# applications and form the backbone of the async/await keywords.

In C#, there are three ways to schedule asynchronous code to run using the Task class and its generic equivalent Task<T>.

Creating a New Task

You'll start off with the simplest form, one that performs an operation but does not return a result back to the caller. You can declare a Task instance by calling any of the Task constructors and passing in an Action based delegate. This delegate contains the actual code to be executed at some point in the future. Many of the constructor overloads allow cancellation tokens and creation options to further control how the Task runs.

Some of the commonly used constructors are...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime