任务与线程差异 [英] Task vs Thread differences
问题描述
我是并行编程的新手..NET 中有两个可用的类:Task
和 Thread
.
I'm new to parallel programming. There are two classes available in .NET: Task
and Thread
.
所以,我的问题是:
- 这些类之间有什么区别?
- 什么时候使用
Thread
而不是Task
更好(反之亦然)?
- What is the difference between those classes?
- When is it better to use
Thread
overTask
(and vice-versa)?
推荐答案
Thread
是一个低级概念:如果你直接启动一个线程,你知道它将是一个单独的线程,而不是在线程池等上执行.
Thread
is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.
Task
不仅仅是在何处运行某些代码"的抽象——它实际上只是对未来结果的承诺".举一些不同的例子:
Task
is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:
Task.Delay
不需要任何实际的 CPU 时间;这就像设置一个定时器在未来关闭WebClient.DownloadStringTaskAsync
返回的任务在本地不会占用太多 CPU 时间;它代表的结果可能大部分时间都花在网络延迟或远程工作上(在网络服务器上)Task.Run()
返回的任务确实 在说我希望你单独执行这段代码";执行该代码的确切线程取决于多种因素.
Task.Delay
doesn't need any actual CPU time; it's just like setting a timer to go off in the future- A task returned by
WebClient.DownloadStringTaskAsync
won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server) - A task returned by
Task.Run()
really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.
请注意,Task
抽象对于 C# 5 中的异步支持至关重要.
Note that the Task<T>
abstraction is pivotal to the async support in C# 5.
一般来说,我建议您尽可能使用更高级别的抽象:在现代 C# 代码中,您应该很少需要显式启动自己的线程.
In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.
这篇关于任务与线程差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!