Reader Level:
ARTICLE

Writing Your First Multithreading Application

Posted by Mahesh Chand Articles | Multithreading in C# February 14, 2001
If you have never written a multithreading application in C# or .NET, this application might be helpful for you.
  • 0
  • 0
  • 17685
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;

COMMENT USING

Trending up