[Serializable] |
When you create a ThreadStart delegate, you identify the method that will handle the event. To associate the event handler with your event, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate.
For an example that demonstrates creating a ThreadStart delegate, see Start. For more information about event handler delegates, see the conceptual topic at MSDN: eventsdelegates.
class WorkerThreadHandler { public TcpListener myTcpListener; public void HandleThread() { Thread currentThread = Thread.CurrentThread; Socket mySocket = myTcpListener.AcceptSocket(); string message = "Thread Name: " + currentThread.Name + "\r\nThread Apartment State: " + currentThread.ApartmentState.ToString() + "\r\nThread State: " + currentThread.ThreadState.ToString(); Console.WriteLine(message); byte[] buf = System.Text.Encoding.ASCII.GetBytes(message.ToCharArray()); mySocket.Send(buf); Console.WriteLine("Closing connection with client."); mySocket.Close(); } } public class MainThreadHandler { private TcpListener myTcpListener; public MainThreadHandler() { myTcpListener = new TcpListener(10000); myTcpListener.Start(); Console.WriteLine("Listener started. Press Ctrl+Break to stop."); while (true) { while (!myTcpListener.Pending()) { Thread.Sleep(1000); } WorkerThreadHandler myWorkerThreadHandler = new WorkerThreadHandler(); myWorkerThreadHandler.myTcpListener = this.myTcpListener; ThreadStart myThreadStart = new ThreadStart(myWorkerThreadHandler.HandleThread); Thread myWorkerThread = new Thread(myThreadStart); myWorkerThread.Name = "Created at " + DateTime.Now.ToString(); myWorkerThread.Start(); } } } // Server output upon telnet connection from client at port 10000: // Listener started. Press Ctrl+Break to stop. // Thread Name: Created at 8/15/2001 8:40:28 PM // Thread Apartment State: MTA // Thread State: Running // Closing connection with client.
Hierarchy: