Hello task C#. NET

This shows how to start a simple task, but it doesn’t begin to illustrate the power of the Task Programming Library. This shows you the basics. If you have used .NET classic threads, you will see that standardizing the building blocks for creating and managing tasks can drastically reduce the amount of code you have to write to create a parallel application. If you are new to parallel programming, then you should take the time to read through each of the sections – these are techniques that you will use in every program that you write.

We will start with the Task class, which is at the heart of the Task Programming Library (TPL). I’ll show you how to use the new standardization features to create and start different types of Task, cancel them, wait for them to complete, and read their results, as well as how to deal with exceptions. To start, take a quick look at the first code listing; it includes some key building blocks that you’ll see throughout this book and use in your own code. Look at the imported namespace:

using System.Threading.Tasks;
This namespace is one that we will be spending a lot of time with, and you will see it in almost all of the examples in this book; it contains the key classes for parallel programming. Another important namespace is System.Threading, which you may recognize as the home of the classic .NET threading classes. This namespace contains classes we’ll use when we come to coordinate the work of several tasks in "coordinating tasks".

The most important part of the first listing is the following:

This is your first sight of the System.Threading.Tasks.Task class, the fundamental class for parallel programming. We use the static Task.Factory.StartNew() method to create a simple Task whose body prints a message to the console. This is the simplest way to create a task that requires no input data and produces no result. You’ll learn how to create and start more complicated tasks in the following sections.

And that is our first (simple) parallel program. Running the program produces the following result:

Main method complete. Press enter to finish.

Hello World.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C#. NET Topics