Posts

Showing posts from March, 2014

Task Library: Common Patterns

Creating a new task

void Main() { Console.WriteLine ("I'm the main thread, starting a new task. My ID: " + Thread.CurrentThread.ManagedThreadId); //the task is started immediately Task t = Task.Factory.StartNew(() => { Console.WriteLine ("I'm a task running concurrently with the thread that started me. My ID: " + Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine ("I'm going away. My ID: " + Thread.CurrentThread.ManagedThreadId); }


I'm the main thread, starting a new task. My ID: 20 I'm going away. My ID: 20 I'm a task running concurrently with the thread that started me. My ID: 24

The method Task.Factory.StartNew() creates a task and immediately starts it. If we want to control when a task starts, we can instantiate a new Task object and call Start() on it.

For e.g.

void Main() { Console.WriteLine ("I'm the main thread, starting…