将参数传递给线程

本文关键字:线程 参数传递 | 更新日期: 2023-09-27 18:27:24

我在使用线程时遇到问题。有一个类是这样的:

public class MyThread
{
    public void Thread1(int a)
    {
        for (int i = 0; i < 1000000; i++)
        {
            j++;
            for (int i1 = 0; i1 < 1000; i1++)
            {
                j++;
            }
        }
        MessageBox.Show("Done From Class");
    }
}

我使用下面的代码来使用它:

private void button1_Click(object sender, EventArgs e)
{
    MyThread thr = new MyThread();
    Thread tid1 = new Thread(new ThreadStart(thr.Thread1));
    tid1.Start();
    MessageBox.Show("Done");
}

由于Thread1参数(int a),我收到错误,当我没有任何参数时就没有任何问题。我该怎么修?

将参数传递给线程

首选方法是第一种方法,因为您可以将多个参数传递给方法,而不必一直强制转换为对象。

Thread t= new Thread(() => thr.Thread1(yourparameter));
t.Start();

或者,在向线程传递参数时,需要使用parameterised线程。你也可以做

Thread t = new Thread (new ParameterizedThreadStart(thr.Thread1));
t.Start (yourparameter);

当然,在第二个例子中,参数必须是对象类型。

线程接受单个object参数:

public void Thread1(object a1)
{
    int a = (int)a1;
    ...
}

像这样传递:

Thread t = new Thread(Thread1);
t.Start(100);

您通常不需要建立委托。从C#2.0开始,执行new ThreadStart(...)通常是无用的。

另一个(常见的)解决方案是将Thread1放在另一个对象中:

public class MyThread
{
    public int A;
    public void Thread1()
    {
        // you can use this.A from here
    }
}
var myt = new MyThread();
myt.A = 100;
var t = new Thread(myt.Thread1)
t.Start();

这是因为委托具有对方法的包含对象的引用。很明显,通过这种方式,您将失去对调用方对象的访问权限。。。但你可以这样做:

public class MyThread
{
    public int A;
    public CallerType ParentThis;
    public void Thread1()
    {
        // you can use this.A from here
        // You can use ParentThis.Something to access the caller
    }
}
var myt = new MyThread();
myt.A = 100;
myt.ParentThis = this;
var t = new Thread(myt.Thread1)
t.Start();

最后一种常见的方法是使用闭包,如Ehsan Ullah() =>的示例)所建议的