Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tasks vs Threads in .NET 4.5

Tags:

c#

.net

Well in .Net 4, There is the new Tasks feature and i was wondering if i can rely on it alog with Async/Await in .Net 4.5 for all the method(s) that i want to execute asynchronously or there are some situations that i will have to use a separate Thread, specially that i have read that Task.Run uses a ThreadPool to execute the method asynchronously.

Conclusion : Is using a combination of Async/Await along with Tasks can free me of using Threads ?

like image 951
Roman Ratskey Avatar asked Mar 01 '13 20:03

Roman Ratskey


1 Answers

If you specify the TaskCreationOptions.LongRunning option (there is an equivalent for continuations as well) then the task will not use a thread pool thread, it will use a regular Thread. Technically this is an implementation detail and is not in the specs, but it's not a completely unreasonable assumption to rely on.

Given that, you should be able to do anything using Task that you could do with Thread directly.

The primary case that comes to mind for where someone might want to use Thread directly would be in creating your own parallel library, assuming you choose not to build it on top of the TPL. While it's not significant in the context of a business application, when creating your own library you may need access to underlying details of a specific Thread object, or you may want to avoid the overhead (small as it is) of using Tasks.

And then of course, if you're not yet using .NET 4.0 you don't have the option of using Task.

like image 196
Servy Avatar answered Sep 18 '22 23:09

Servy