C# 线程 -ThreadStart 委托(delegate)

标签 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;
        }


    }

如何解决?

最佳答案

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

其次,ParameterizedThreadStart 的参数只是object,因此您需要更改您的ProcessPerson 代码以从 转换objectPerson

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

关于C# 线程 -ThreadStart 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1782210/

相关文章:

multithreading - RxJava和多线程变量

c# - 如何知道 datagridview 中的特定复选框是否被选中?

c# - 发送时无法立即完成非阻塞套接字操作

c# - Visual Studio IIS 项目 HttpContext.Current.User.Identity.Current 为空

C# 共享内存缓存

c++ - 有什么方法可以知道线程使用了多少内存?

c - For inside for - 如何在不花时间创建线程的情况下进行内部并行

Android,如何在启动其他 Activity 时保持 CountDownTimer 运行

c# - 我需要帮助使用 lambda 表达式在 Entity Framework 上下文中查找记录

java - Android中的Java多线程