任务VS线程差异线程、差异、任务、VS

由网友(嫑吢丕)分享简介:我是新来的并行编程。有在.NET提供两类:工作和发。 I'm new to parallel programming. There are two classes available in .NET: Task and Thread. 所以,问题是:什么是这些类之间的区别是什么?什么时候最好使用发当工作?So,...

我是新来的并行编程。有在.NET提供两类:工作

I'm new to parallel programming. There are two classes available in .NET: Task and Thread.

所以,问题是:什么是这些类之间的区别是什么?什么时候最好使用工作

So, the question is: What is difference between those classes? When is it better to use Thread and when Task?

推荐答案

是一个低层次的概念:如果你直接启动一个线程,你的知道的将是一个单独的线程,而不是执行的线程池等。

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.

工作更比不过跑哪里去了一些code只是一个抽象的概念 - 它实际上只是因此,在未来的希望。所以一些不同的例子:

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时间任务;这是再presenting一个结果,很可能要花费其大部分时间的网络延迟或远程工作(在Web服务器上) 按返回的任务Task.Run()真正的是的说:我希望你能单独执行此code;即code在其上执行的确切线程依赖于许多因素。 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.

注意任务< T> 抽象是关键,在C#中的异步支持5

Note that the Task<T> abstraction is pivotal to the async support in C# 5.

在一般情况下,我建议您使用更高层次的抽象的地方,你可以:在现代的C#code,你应该很少需要显式地开始自己的线程

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.

阅读全文

相关推荐

最新文章