What is the difference between task and thread?

后端 未结 8 1600
庸人自扰
庸人自扰 2020-11-22 02:45

In C# 4.0, we have Task in the System.Threading.Tasks namespace. What is the true difference between Thread and Task. I did s

8条回答
  •  忘了有多久
    2020-11-22 03:25

    A Task can be seen as a convenient and easy way to execute something asynchronously and in parallel.

    Normally a Task is all you need, I cannot remember if I have ever used a thread for something else than experimentation.

    You can accomplish the same with a thread (with lots of effort) as you can with a task.

    Thread

    int result = 0;
    Thread thread = new System.Threading.Thread(() => { 
        result = 1; 
    });
    thread.Start();
    thread.Join();
    Console.WriteLine(result); //is 1
    

    Task

    int result = await Task.Run(() => {
        return 1; 
    });
    Console.WriteLine(result); //is 1
    

    A task will by default use the Threadpool, which saves resources as creating threads can be expensive. You can see a Task as a higher level abstraction upon threads.

    As this article points out, task provides following powerful features over thread.

    • Tasks are tuned for leveraging multicores processors.

    • If system has multiple tasks then it make use of the CLR thread pool internally, and so do not have the overhead associated with creating a dedicated thread using the Thread. Also reduce the context switching time among multiple threads.

    • Task can return a result.There is no direct mechanism to return the result from thread.
    • Wait on a set of tasks, without a signaling construct.

    • We can chain tasks together to execute one after the other.

    • Establish a parent/child relationship when one task is started from another task.

    • Child task exception can propagate to parent task.

    • Task support cancellation through the use of cancellation tokens.

    • Asynchronous implementation is easy in task, using’ async’ and ‘await’ keywords.

提交回复
热议问题