Sunday, 15 September 2013

Thread vs task in c#


First ans

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 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 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.
Note that the Task<T> abstraction is pivotal to the async support in C# 5.
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.


Second ANS

ask is a higher level concept and that means:
  1. You can't use Abort/ThreadAbortedException, you should support cancel in your "business code" periodically testing IsCancellationRequested flag (and for this manage timeoutless connections otherwise you will never get a chance to test a flag).
  2. Also there are no thread.Suspend and thread.Resume methods functionality.
  3. But you have two new tools: continuations, and Nested/Child Tasks
Those two samples demonstrate the syntax:
Task.Factory.ContinueWhenAll(
                            tasks,
                            () =>
                            {
                                int answer = tasks[0].Result + tasks[1].Result;
                                Console.WriteLine("The answer is {0}", answer);
                            });

//StartNew - starts task immediately, parent ends whith child
var parent = Task.Factory.StartNew(() => 
    {
        var child = Task.Factory.StartNew(() =>
        {
            //...
        });
    },  TaskCreationOptions.AttachedToParent);


 3Rd ANS

Suppose you are running a book delivery company. You have four cars and four drivers. A car is a thread, a driver is a processor, and a book delivery is a task. The problem you face is how to efficiently schedule the drivers and cars so that the tasks get done as quickly as possible.
Where things get weird is when there are more cars (threads) than drivers (processors). What happens then is halfway through a trip the driver parks one car (suspends the thread) and gets into a different car (switches context), drives that one around for a while performing tasks, and then eventually comes back to the first car. Obviously that is not as efficient as one driver staying in one car.
The idea of task-based parallism is to break up the work into small tasks that can produce results in the future, and then efficiently allocate exactly as many threads as there are processors so that you don't waste time context switching. In practice, it usually does not work out that nicely, but that's the idea.
which one is better, task or thread?
The question cannot be answered because it doesn't make any sense. Which is better, a book to deliver to a customer, or a car to deliver it in? A car is a device that can be used to deliver a book; those two things are not things you can sensibly describe as "better" or "worse" than the other. It's like asking "which is better, a hole or a drill?"

No comments:

Post a Comment