C# Threads -ThreadStart Delegate
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?
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();
}
Your function declaration should look like this:
static void ProcessPerson(object p)
Inside ProcessPerson
, you can cast 'p' to a Person
object.
精彩评论