C# 线程 -ThreadStart 委托

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1782210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:46:43  来源:igfitidea点击:

C# Threads -ThreadStart Delegate

c#multithreading

提问by user215675

The execution of the following code yields error :No overloads of ProcessPerson Matches ThreadStart.

以下代码的执行产生错误: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;
        }


    }

How to fix it?

如何解决?

采纳答案by Jon Skeet

Firstly, you want ParameterizedThreadStart- ThreadStartitself doesn't have any parameters.

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

Secondly, the parameter to ParameterizedThreadStartis just object, so you'll need to change your ProcessPersoncode to cast from objectto Person.

其次,参数 toParameterizedThreadStart只是object,因此您需要将ProcessPerson代码更改为从objectto 转换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:

但是,如果您使用的是 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();
}

回答by Richard Nienaber

Your function declaration should look like this:

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

static void ProcessPerson(object p)

Inside ProcessPerson, you can cast 'p' to a Personobject.

在里面ProcessPerson,您可以将 'p' 转换为一个Person对象。