C#Threads -ThreadStart Delegate

时间:2009-11-23 10:11:03

标签: c# multithreading

执行以下代码会产生错误:ProcessPerson没有重载匹配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;
        }


    }

如何解决?

2 个答案:

答案 0 :(得分:31)

首先,您希望ParameterizedThreadStart - ThreadStart本身没有任何参数。

其次,ParameterizedThreadStart的参数仅为object,因此您需要将ProcessPerson代码更改为从object转换为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表达式:

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();
}

答案 1 :(得分:2)

您的函数声明应如下所示:

static void ProcessPerson(object p)

ProcessPerson内,您可以将'p'投射到Person对象。