C# Threads -ThreadStart Delegate

c#, multithreading

Solution

Firstly, you want `ParameterizedThreadStart` - `ThreadStart` itself doesn't have any parameters.

Secondly, the parameter to `ParameterizedThreadStart` is just `object`, so you'll need to change your `ProcessPerson` code to cast from `object` to `Person`.

static void Main()
{
    Person p = new Person();
    p.Id = "cs0001";
    p.Name = "William";
    Thread th = new Thread(new ParameterizedThreadStart(ProcessPerson));
    th.Start(p);
}

static void ProcessPerson(object o)
{
    Person p = (Person) o;
    Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
}

However, if you're using C# 2 or C# 3 a cleaner solution is to use an anonymous method or lambda expression:

static void ProcessPerson(Person p)
{
    Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
}

// C# 2
static void Main()
{
    Person p = new Person();
    p.Id = "cs0001";
    p.Name = "William";
    Thread th = new Thread(delegate() { ProcessPerson(p); });
    th.Start();
}

// C# 3
static void Main()
{
    Person p = new Person();
    p.Id = "cs0001";
    p.Name = "William";
    Thread th = new Thread(() => ProcessPerson(p));
    th.Start();
}

Problem

The execution of the following code yields error :No overloads of ProcessPerson Matches ThreadStart. ``` public class Test { static void Main() { Person p = new Person(); p.Id = "cs0001"; p.Name = "William"; Thread th = new Thread(new ThreadStart(ProcessPerson)); th.Start(p); } static void ProcessPerson(Person p) { Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name); } } public class Person { public string Id { get; set; } public string Name { get; set; } } ``` How to fix it?

Original source