Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 4 Task Class Tutorial

.NET 4 has a Class - Task. It's pretty interesting and I would like to start using it. For example, I would like to create a very simple Task-based files downloader, with the ability to cancel with every download. Can anyone introduce me to some sample code of doing that? I would like to have an list of running tasks and would like to be able to cancel any of them.

P.S. Code sample can be not functioning I just want to know how to use these things in a best way.

like image 254
Lukas Šalkauskas Avatar asked Oct 18 '10 11:10

Lukas Šalkauskas


People also ask

How are tasks created in .NET framework?

NET framework provides Threading. Tasks class to let you create tasks and run them asynchronously. A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.

What is Task <> C#?

A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the . NET Framework 4. The Task object is typically executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.

What is difference between thread and Task?

A thread is one of the many possible workers which performs that task. In . NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

Does Task use ThreadPool C#?

By default, TPL types like Task and Task<TResult> use thread pool threads to run tasks. You can also use the thread pool by calling ThreadPool.


2 Answers

If you want to be able to cancel one or more tasks, you need to create a CancellationTokenSource and pass in the CancellationToken of this to each Task. If all the Tasks must be cancelled using the same operation, they can share the same token. If each task can be cancelled independently of the other, you need to have separate CancellationTokens. Please check this guide for examples of how to cancel parallel tasks.

like image 78
Brian Rasmussen Avatar answered Sep 22 '22 09:09

Brian Rasmussen


Various samples, simple and more advanced, have been given on the various PFX (Parallel Framework Extension)—of which Task is part—team blog: http://blogs.msdn.com/b/pfxteam/

like image 33
Richard Avatar answered Sep 24 '22 09:09

Richard