Threads vs. Tasks

Source: Internet
Author: User

Posted on Friday, October

. Net have three low-level mechanisms to run code in parallel: Thread , ThreadPool , and Task . These three mechanism serve different purposes. Thread

ThreadRepresents an actual os-level thread, with its own stack and kernel resources. (Technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread Allows the highest degree of control; You can Abort() or Suspend() or Resume() a thread (though the very bad idea), you can observe it state, and you can set thre Ad-level properties like the stack size, apartment state, or culture.

The problem with is, the Thread OS threads is costly. Each thread has consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the Proces Sor context-switch between threads. Instead, it's better to has a small pool of threads execute your code as work becomes available.

There there is no alternative Thread . If you need to specify the name (for debugging purposes) or the ' apartment state ' (to show a UI), you must create your own c2/> (note that has multiple UI threads is generally a bad idea). Also, if you want to maintain an object that's owned by a single thread and can have only been used by that thread, it is much easier to explicitly create a Thread instance for it so can easily check whether code trying to use it is Runni ng on the correct thread. ThreadPool

ThreadPoolis a wrapper around a pool of threads maintained by the CLR. ThreadPoolgives you no control at all; can submit work to execute at some point, and you can control the size of the pool, But you can ' t set anything else. You can ' t even tell when the pool would start running the work of your submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the ThreadPool, it can get full, and later work that you submit can End up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no-to-find out when a work item has been completed (unlike Thread.Join() ), nor a-by- Result. Therefore, is best used for short ThreadPool operations where the caller does not need the result. Task

Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like ThreadPool the, a task does not to create its own OS thread. Instead, tasks is executed by a TaskScheduler ; The default scheduler simply runs on the ThreadPool.

Unlike the ThreadPool, Task also allows you to find if it finishes, and (via the generic Task<T> ) to return a result. You can call on a ContinueWith() existing Task to make it run more code once the task finishes (if it ' s already finished, it wil L run the callback immediately). If the task is generic, would ContinueWith() pass you the task's result, allowing you-to-run more code that uses it.

You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result proper TY). Like Thread.Join() , this would block the calling thread until the task finishes. Synchronously waiting for a task was usually bad idea; It prevents the calling thread from doing any other work, and can also leads to deadlocks if the task ends up waiting (even Asynchronously) for the current thread.

Since tasks still run on the ThreadPool, they should not being used for long-running operations, Since they can still fill up The thread pool and block new work. Instead, Task provides a LongRunning option, which'll tell the- TaskScheduler spin up a new thread rather than running on the thread Pool.

All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C # 5 await , and modern async methods in the BCL , is all built on Task . Conclusion

The bottom line was that was almost always the best Task option; it provides a much more powerful API and avoids wasting OS Threads.

The only reasons to explicitly create your own Thread s in modern code is setting Per-thread options, or maintaining a pers Istent thread, needs to maintain its own identity.

http://blog.slaks.net/2013-10-11/threads-vs-tasks/

Threads vs. Tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.