.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.
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.
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.
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.
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.
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 Task
s 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 CancellationToken
s. Please check this guide for examples of how to cancel parallel tasks.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With