简体   繁体   English

.NET 4.5中的任务与线程

[英]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. .Net 4 ,有一个新的Tasks功能,我想知道我是否可以通过.Net 4.5 Async/Await依赖它来Async/Await执行所有要使用的所有方法,或者在某些情况下我将必须使用单独的Thread ,特别是我已阅读Task.Run使用ThreadPool异步执行该方法。

Conclusion : Is using a combination of Async/Await along with Tasks can free me of using Threads ? 结论:将Async/AwaitTasks结合使用可以使我摆脱使用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 . 如果您指定TaskCreationOptions.LongRunning选项(也有等效的延续),则该任务将不使用线程池线程,而将使用常规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. 鉴于此,您应该能够使用Task直接执行与Thread一起执行的任何操作。

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. 某个人可能想直接使用Thread的主要情况是,创建您自己的并行库,假设您选择不将其构建在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 . 尽管在业务应用程序的上下文中它并不重要,但是在创建自己的库时,您可能需要访问特定Thread对象的基础详细信息,或者您可能希望避免使用Tasks的开销(虽然很小)。

And then of course, if you're not yet using .NET 4.0 you don't have the option of using Task . 然后,当然,如果您尚未使用.NET 4.0,则不能选择使用Task

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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