System.Threading.ThreadStart Delegate

Assembly: Mscorlib.dll
Namespace: System.Threading
Summary
Represents the method that will handle the Start event of the Thread class.
C# Syntax:
[Serializable]
public delegate void ThreadStart();
Remarks
When a thread is created, the new instance of the Thread class is created using a constructor that takes the ThreadStart delegate as its only parameter. However, the thread does not begin executing until the Thread.Start method is invoked. When Start is called, execution begins at the first line of the method referenced by the ThreadStart delegate.

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.

Example
	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.

    
See also:
System.Threading Namespace | Thread | AppDomain | MSDN: eventsdelegates

Hierarchy:

Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.