PROWARE technologies
PROWARE technologies

Working with Threads/Threading in .NET

Working with threads in .NET is practically identical to using them in the Windows API.

Using the .NET Thread class, threads can be created and controlled. After a Thread object is created, use the Start() method.

using System;
using System.Threading;

class ThreadExample
{
	static void Main()
	{
		var thread1 = new Thread(ThreadFunc);
		thread1.Start();
		Console.WriteLine("Main thread");
	}
	static void ThreadFunc()
	{
		Console.WriteLine("In a thread");
	}
}

Passing Data to Threads

A parameter(s) can be passed to the new thread's method but it must be passed as an object and then type cast to the right datatype.

using System;
using System.Threading;

class ThreadExample
{
	public struct Data
	{
		public string first;
		public string last;
	}
	static void Main()
	{
		Data d;
		d.first = "abc";
		d.last = "xyz";

		var thread1 = new Thread(ThreadFunc);
		thread1.Start(d);
		Console.WriteLine("Main thread");
	}
	static void ThreadFunc(object o)
	{
		Data d2 = (Data)o;
		Console.WriteLine("In a thread with parameter: " + d2.first);
	}
}

Background Threads

The application's process continues to run for as long as at least one foreground thread is running. If this is a problem then solve it by using background threads.

Specify the property IsBackground = true to create background threads.

using System;
using System.Threading;

class ThreadExample
{
	static void Main()
	{
		var thread1 = new Thread(ThreadFunc) { IsBackground = true };
		thread1.Start();
		Console.WriteLine("Main thread");
	}
	static void ThreadFunc()
	{
		Console.WriteLine("In a thread");
	}
}