Creating threads and using parameters
In this section, we look at the creation of threads. First, we will see how to create parameterless threads in the foreground and the background. Let’s define both foreground and background threads as follows:
- Foreground threads: By default, threads run in the foreground. A process will continue to run if, at least, one foreground thread is running. Should the
Main
method be complete and the foreground thread is still running, the process will remain active until the foreground thread terminates. - Background threads: Background threads are created in the same way as foreground threads. The main difference is that you must explicitly set the thread to run in the background.
The following code shows how to create and run a foreground thread:
var foregroundThread = new Thread(methodName);
foregroundThread.Start();
To create and run a background thread, you run the following code:
var backgroundThread = new Thread...