This is a mirror of official site: http://jasper-net.blogspot.com/

Task != Thread

| Monday, December 19, 2011
whenever I teaching the Tpl Task subject I continually repeating the mantra which say that "task is a metadata/context of execution and it does not really responsible for the actual execution".

Task is a data structure which hold information about code execution, it's hold the delegate which will be execute, status, state, result, exception synchronization object, ext...
but the responsibility of the execution is actually belong to the Task Scheduler.

in matter of fact task can be execute synchronously.

    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    Task t = new Task(() =>
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId));
    t.RunSynchronously();


by default it is execute on a thread pool worker thread but it can be execute on non thread pool thread (using the TaskCreationOption.LongRunning overload).

    Task.Factory.StartNew(() =>
        Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread));
    Task.Factory.StartNew(() =>
            Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread),
            TaskCreationOptions.LongRunning);

it can be benefit from IOCP (IO Completion Port) in order to avoid thread pool starvation (when performing IO operations). IO operation are not CPU bounded operation, those operation performed by the hard disk controller, the network card, ext...


Read more: Bnaya Eshet
QR: task-thread.aspx

Posted via email from Jasper-net

0 comments: