ThreadStart Delegate

Namespace: System.Threading

Represents a method to be executed by a new thread.

Syntax

public delegate void ThreadStart();

Remarks

The ThreadStart delegate is used to specify the entry point for a thread. When you create a new Thread object, you can pass an instance of the ThreadStart delegate to the Thread constructor. The delegate points to the method that will be executed when the thread begins its execution.

The method that the ThreadStart delegate points to must not accept any parameters and must not return a value (i.e., it must have a void return type).

Constructors

The ThreadStart delegate does not have public constructors. You typically create an instance by using the delegate constructor syntax or by using the shorthand syntax for creating delegate instances from methods.

Methods

Method signature that the ThreadStart delegate can represent

A method that can be used with ThreadStart must match the following signature:

void MyThreadMethod();

Thread Safety

Thread safety is the responsibility of the developer. Ensure that any shared data accessed by threads created with ThreadStart is protected using appropriate synchronization mechanisms (e.g., locks, mutexes, semaphores).

Examples

Creating and starting a thread

using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Define the method to be executed by the thread
        ThreadStart ts = new ThreadStart(ThreadMethod);

        // Create a new thread and pass the ThreadStart delegate
        Thread newThread = new Thread(ts);

        // Start the thread
        newThread.Start();

        Console.WriteLine("Main thread finished.");
    }

    public static void ThreadMethod()
    {
        Console.WriteLine("This is the new thread.");
        // Simulate some work
        Thread.Sleep(1000);
        Console.WriteLine("New thread finished.");
    }
}

Using shorthand for delegate creation

using System;
using System.Threading;

public class ExampleShorthand
{
    public static void Main()
    {
        // Using shorthand syntax to create the ThreadStart delegate
        Thread newThread = new Thread(ShorthandThreadMethod);
        newThread.Start();

        Console.WriteLine("Main thread finished.");
    }

    public static void ShorthandThreadMethod()
    {
        Console.WriteLine("This is the new thread (shorthand).");
        Thread.Sleep(500);
        Console.WriteLine("New thread finished (shorthand).");
    }
}

Requirements

Namespace: System.Threading

Assembly: System.Runtime.dll