Creating Background Thread C# with Example



Creating Background Thread C# with Example

 using System;
using System.Threading;
using System.Windows.Forms;

namespace CSharpMultiThreading
{
	public class Printer
	{
		//Step1: Method to be executed as Secondary Thread
		public void PrintNumbers()
		{
			// Display Thread info.
			Console.WriteLine("-> {0} is executing PrintNumbers()",Thread.CurrentThread.Name);

			// Print out numbers.
			Console.Write("Your numbers: ");
			for(int i = 0; i < 10; i++)
			{
				Console.Write("{0}, ", i);
				Thread.Sleep(2000);
			}
		}
	}

    class UsingThreadStartDelegate
    {
		static void Main(string[] args)
		{
			Console.Write("Do you want [1] or [2] threads? ");
			string threadCount = Console.ReadLine();

			// Name the current thread.
			Thread primaryThread = Thread.CurrentThread;
			primaryThread.Name = "Primary";

			// Display Thread info.
			Console.WriteLine("-> {0} is executing Main()",Thread.CurrentThread.Name);

			// Make worker class.
			Printer p = new Printer();

			//Step2: ThreadStart Delegate Object
			ThreadStart secondaryThreadCode = new ThreadStart(p.PrintNumbers);
			
			switch(threadCount)
			{
				case "2":
					// Step3: Create New Thread.
					Thread backgroundThread = new Thread(secondaryThreadCode);
					
					// Step4: Initialize Properties with Newly Created Thread.
					backgroundThread.Name = "Secondary";
					backgroundThread.IsBackground = true;	//Creating Background Thread
					
					// Step5: Start the Newly Created Thread.
					backgroundThread.Start();
					break;
				
				case "1":
					p.PrintNumbers();
					break;
				
				default:
					Console.WriteLine("I don't know what you want...you get 1 thread.");
					goto case "1";
			}
			// Do some additional work.
			MessageBox.Show("I'm busy!", "Work on main thread...");
		}
    }
}
 

0 Comment's

Comment Form

Submit Comment