.NET 4 Task Class Tutorial

Lukas Šalkauskas picture Lukas Šalkauskas · Oct 18, 2010 · Viewed 23.8k times · Source

.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.

Answer

Brian Rasmussen picture Brian Rasmussen · Oct 18, 2010

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.