C#线程-ThreadStart代表 [英] C# Threads -ThreadStart Delegate
问题描述
下面的代码错误产量的执行:ProcessPerson没有重载匹配的ThreadStart。
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?
推荐答案
首先,你想要的 ParameterizedThreadStart
- 的 的ThreadStart
本身不具有任何参数。
Firstly, you want ParameterizedThreadStart
- ThreadStart
itself doesn't have any parameters.
其次,参数 ParameterizedThreadStart
就是对象
,所以你需要改变你的 ProcessPerson
代码从对象
转换为人
。
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);
}
不过,如果你正在使用C#2或C#3的解决方法就是使用匿名方法或lambda表达式:
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();
}
这篇关于C#线程-ThreadStart代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!