Exercise: First thread (again)

In this exercise you will try some simple features of the thread APIĀ 

Getting started

Make a new project in Visual Studio.

In a class make a method void Print() which loops 10 times, print the same message (like "hello world") to the screen.

From the Main() call the Print() method 4 times.

Add threads

Refactor the Main() to use 4 Thread objects to call Print() 4 times.

Parameter: Message

Add a parameter string Message to the Print() method.

The Print() method must print the message specified.

Adapt Main()s, that the 4 Thread object now print different messages. Hint use a lambda expression: new Thread(() => print("some message"));

Paramater: NumberOfTimes

Add another parameter int numberOfTimes to the Print() method.

The Print() method must print the message "NumberOfTimes" times.

Adapt Main() ...

Name the thread

Assign each Thread object a name using the Name property of Thread.

Print the Name in the Print() method.

Hint: Thread.CurrentThread.Name gets the name of the current thread (useful in the Print method)

Sleep

Try the Thread.Sleep(...) method in Print().

Join

Try to Join the Thread objects, and after that Main() should print "This is it".

Priorities

Add different priorities to the Thread object before you start them.

Adapt the Print() method to write the priority of the current thread: Thread.CurrentThread.Name

Does the priorities have any effect?

Thread pool

Change Main() to use a thread pool to manage your Thread objects.

Threads run by the thread pool are background threads. They are killed as soon as the foreground thread (Main) is done. Hint: Add a Console.ReadLine() to the end of Main.