SoFunction
Updated on 2025-05-20

Implementation of ThreadStart Delegation in C#

Entrustment:

ThreadStartis a built-in delegate type in .NET that represents a method with no parameters and no return value. Its definition is as follows:

public delegate void ThreadStart();
  • Usually used to define the entry method of thread.

  • List<ThreadStart>
    This is a generic collection that is used to store multipleThreadStartDelegate instance. Each delegation represents a task to be executed.

  • Overall function:
    Create a thread task queue to save multiple methods that need to be executed through threads.

2. Typical usage scenarios

private List<ThreadStart> delegates = new List<ThreadStart>();

(1) Multitasking queue management

// Add tasks to queue(() =&gt; ("Task 1"));
(() =&gt; ("", "Hello"));

// Start the thread to execute all tasksforeach (var task in delegates)
{
    new Thread(task).Start();
}

(2) Delay execution control

// Collect tasks first(() =&gt; DownloadFile(url1));
(() =&gt; ProcessData(data));

// Trigger execution at the appropriate timevoid ExecuteAllTasks()
{
    foreach (var task in delegates)
    {
        new Thread(task).Start();
    }
}

3. Technical details

The relationship between delegate and thread

  • EachThreadStartDelegation can be passed toThreadConstructor, as a method to execute when thread starts.

  • Example:

ThreadStart task = () => ("Running in thread");
Thread thread = new Thread(task);
();

Thread safety precautions

  • Non-thread-safe collection:
    List<T>It is not thread-safe itself. If multiple threads modify the collection at the same time (such as adding/deleting tasks), a lock is required:

private readonly object _lock = new object();

void AddTask(ThreadStart task)
{
    lock (_lock)
    {
        (task);
    }
}

4. Complete usage example

using System;
using ;
using ;

class TaskScheduler
{
    private List&lt;ThreadStart&gt; _tasks = new List&lt;ThreadStart&gt;();
    private readonly object _lock = new object();

    public void AddTask(Action action)
    {
        lock (_lock)
        {
            _tasks.Add(new ThreadStart(action));
        }
    }

    public void ExecuteAll()
    {
        List&lt;Thread&gt; threads = new List&lt;Thread&gt;();
        
        lock (_lock)
        {
            foreach (var task in _tasks)
            {
                Thread thread = new Thread(task);
                (thread);
                ();
            }
            _tasks.Clear();
        }

        // Wait for all threads to complete (optional)        foreach (var thread in threads)
        {
            ();
        }
    }
}

// Use examplevar scheduler = new TaskScheduler();
(() =&gt; ("Task 1"));
(() =&gt; (1000));
();

5. Alternatives (recommended by modern C#)

Use Task and ConcurrentQueue

using ;
using ;

private ConcurrentQueue&lt;Action&gt; _taskQueue = new ConcurrentQueue&lt;Action&gt;();

// Add a task_taskQueue.Enqueue(() =&gt; ("Task 1"));

// Parallel execution(_taskQueue, task =&gt; ());
_taskQueue.Clear();

advantage

  • More efficient thread pool management (byTask

  • Innately thread-safe collection (ConcurrentQueue

  • supportasync/await

6. Key Difference: ThreadStart vs Action

characteristic ThreadStart Action
Return value none (void) none (void)
parameter none Can be equipped with parameters (such asAction<int>
use Dedicated forThreadConstructor General Delegation
Modernity Older API Recommended use

Summarize

  • Original code: Created a traditional thread task queue, suitable for explicit managementThreadScene.

  • Modern alternative: recommendedTask + ConcurrentQueueCombination is more in line with the current .NET concurrent programming best practices.

  • Thread safety: If you insist on using itList<ThreadStart>, thread safety must be ensured through locking mechanism.

Choose the appropriate solution according to actual needs and balance control of fineness and development efficiency.

This is the end of this article about the implementation of ThreadStart delegation in C#. For more related content of ThreadStart delegation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!