简体   繁体   中英

Tasks vs Threads in .NET 4.5

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM