Reader Level:
Articles

Writing Your First Multithreading Application

By Mahesh Chand on Feb 14, 2001
If you have never written a multithreading application in C# or .NET, this application might be helpful for you.
  • 0
  • 0
  • 18551
Download Files:
 

If you have never written a multithreading application in C# or .NET, this application might be helpful for you. In this application, second thread writes data to the console. The Thread class encapsulate the thread functionality in .NET.

You create a new secondary thread by using Thread class constructor. The constructor of the Thread class takes one argument and that is the function you want to execute in secondary thread. This function might be from another class or this class itself. Once you created an instance, you set the priority of the thread by calling Priority method and then call the Start method to start the thread.

You use Abort method to kill a thread. Make sure thread is alive before you kill it.

Another way to create a secondary thread is use ThreadStart. See my Tutorial: Multithreading for Beginners for more details.

public class mt1
{
public static void PrintCurDateTime()
{
Console.WriteLine( " Secondary Thread" );
Console.WriteLine( DateTime.Now.ToLongTimeString() );
}
public static int Main(String[] args)
{
Console.WriteLine("Main Thread \n");
try
{
Thread secThread =
new Thread(new ThreadStart( PrintCurDateTime ) );
secThread.Priority = ThreadPriority.Highest;
secThread.Start();
if ( secThread.IsAlive)
{
secThread.Abort();
}
}
catch (Exception e)
{
Console.WriteLine( e.ToString());
}
return 0;

Mahesh Chand

C# Corner founder, 10-times Microsoft MVP, technical author, and software architect. Mahesh authored his first book, A Programmer’s Guide to ADO.NET in C# with APress at the age of 25. C# Corner is a memb... Read more

COMMENT USING

Trending up