Tuesday, October 27, 2009

Multithreaded Applications

I wrote the following test program, which makes use of several classes in the System.Threading namespace:


using System;
using System.Threading;

namespace ThreadingApp
{
public class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.RunApp();
Console.ReadKey();
}

public void RunApp()
{
ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 1");
ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 2");
ThreadMethod("Thread 3");
ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 4");
Console.WriteLine("Main thread exits.");

Thread myThread = new Thread(new ThreadStart(ThreadCallback));
myThread.Name = "My Thread";
myThread.Priority = ThreadPriority.Highest;
Console.WriteLine("From runapp, {0}.ThreadState={1}", myThread.Name, myThread.ThreadState);
myThread.Start();

}

void ThreadCallback()
{
Console.WriteLine("Calling ThreadCallback");
Console.WriteLine("{0}.ThreadState={1}", Thread.CurrentThread.Name, Thread.CurrentThread.ThreadState);
}

void ThreadMethod(Object stateInfo)
{
String state = (String) stateInfo;
if (Thread.CurrentThread.IsBackground)
{
Console.WriteLine("background thread: " + state);
}
else
{
Console.WriteLine("foreground thread: " + state);
}
}
}
}

/*
Resulting output:

foreground thread: Thread 3
Main thread exits.
background thread: Thread 1
background thread: Thread 2
background thread: Thread 4
From runapp, My Thread.ThreadState=Unstarted
Calling ThreadCallback
My Thread.ThreadState=Running

*/

No comments:

Post a Comment