Friday, January 23, 2015

Overview

Parallel programming is very important to know and C# does it so well. This post is all about the System.Threading namespace. More information can be found here.

Example

How do we make a line of code execute in the background on a separate thread?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Program {
    public static void Main(string[] args) {
        // Start task with the constructor
        var t1 = new Task( () => DoWork(1, 1000) );
        t1.Start();

        // Start task with a factory
        var t2 = Task.Factory.StartNew( () => DoWork(2, 1200) )
                             .ContinueWith( (prevTask) => DoOtherWork(2, 1200) );
    }

    public static void DoWork(int id, int sleepTime) {
        Console.WriteLine("Task {0} starting.", id);
        Thread.sleep(sleepTime);
        Console.WriteLine("Task {0} stopping.", id);
    }

    public static void DoOtherWork(int id, int sleepTime) {
        Console.WriteLine("Other Task {0} starting.", id);
        Thread.sleep(sleepTime);
        Console.WriteLine("Other Task {0} stopping.", id);
    }
}

/*
Task 2 starting.
Task 1 starting.
Task 1 stopping.
Task 2 stopping.
Other Task 2 starting.
Other Task 2 stopping.
 */

Given the code above, how do we wait on the main thread until all the tasks are done?

1
2
3
4
5
6
7
8
9
public static void Main(string[] args) {
    var t1 = Task.Factory.StartNew( () => DoWork(1, 1000) );
    var t2 = Task.Factory.StartNew( () => DoWork(2, 1200) );
    var taskList = new List<Task>{t1, t2};

    // or we could use Task.WaitAny
    Task.WaitAll( taskList.ToArray() );
    Console.WriteLine("Finished all tasks");
}

Random Posts