Write First Threading App In C#

Updated 7/17/2018

if you've never created a multi-threaded app, this is basic introduction of threading in .NET using C#. 

The Thread class represents a thread and provides functionality to create and manage a thread’s lifecycle, and its properties such as status, priority, state.

The Thread class is defined in the System.Threading namespace must be imported before you can use any threading related types.

  1. using System.Threading;

The Thread constructor takes a ThreadStart delegate as a parameter and creates a new thread. The parameter of the ThreadStart is the method that is executed by the new thread. Once a thread it created, it needs to call the Start method to actually start the thread.

The following code snippet creates a new thread, workerThread that will execute code in the Print method.

  1. // Create a secondary thread by passing a ThreadStart delegate
  2. Thread workerThread = new Thread(new ThreadStart(Print));
  3. // Start secondary thread
  4. workerThread.Start();

The Print method is listed below that can be used to execute code to do some background or foreground work.

  1. static void Print()
  2. {
  3. }

Let’s try it.

Open Visual Studio. Create a new .NET Core console project. Delete all code and copy and paste (or type) the code in Listing 1.

  1. using System;
  2. using System.Threading;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. // Create a secondary thread by passing a ThreadStart delegate
  8. Thread workerThread = new Thread(new ThreadStart(Print));
  9. // Start secondary thread
  10. workerThread.Start();
  11. // Main thread : Print 1 to 10 every 0.2 second.
  12. // Thread.Sleep method is responsible for making the current thread sleep
  13. // in milliseconds. During its sleep, a thread does nothing.
  14. for (int i=0; i< 10; i++)
  15. {
  16. Console.WriteLine($"Main thread: {i}");
  17. Thread.Sleep(200);
  18. }
  19. Console.ReadKey();
  20. }
  21. /// <summary>
  22. /// This code is executed by a secondary thread
  23. /// </summary>
  24. static void Print()
  25. {
  26. for (int i = 11; i < 20; i++)
  27. {
  28. Console.WriteLine($"Worker thread: {i}");
  29. Thread.Sleep(1000);
  30. }
  31. }
  32. }

Listing 1.

The code of Listing 1, the main thread prints 1 to 10 after every 0.2 seconds. The secondary thread prints from 11 to 20 after every 1.0 second. We’re using the delay for the demo purpose, so you can see live how two threads execute code parallelly.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.