Writing Your First Multithreading Application


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;

Up Next
    Ebook Download
    View all
    Learn
    View all