如何在线程中将参数传递给ThreadStart方法?

时间:2022-10-15 15:13:10

How to pass parameters to Thread.ThreadStart() method in C#?

如何在c#中将参数传递给Thread.ThreadStart()方法?

Suppose I have method called 'download'

假设我有一个方法叫做下载

public void download(string filename)
{
    // download code
}

Now I have created one thread in the main method:

现在我在main method中创建了一个线程:

Thread thread = new Thread(new ThreadStart(download(filename));

error method type expected.

错误方法类型的预期。

How can I pass parameters to ThreadStart with target method with parameters?

如何将参数传递给带有参数的目标方法ThreadStart ?

8 个解决方案

#1


589  

The simplest is just

最简单的就是

string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();

The advantage(s) of this (over ParameterizedThreadStart) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object all the time.

这种方法的优点(优于参数化的threadstart)是可以传递多个参数,并且可以在编译时进行检查,而不需要一直从对象中强制转换。

#2


30  

Look at this example:

看看这个例子:

public void RunWorker()
{
    Thread newThread = new Thread(WorkerMethod);
    newThread.Start(ParameterObject);
}

public void WorkerMethod(object parameterObject)
{
    // do your job!
}

You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.

您首先通过将委托传递给worker方法来创建一个线程,然后用一个线程启动它。以对象为参数的Start方法。

So in your case you should use it like this:

所以在你的例子中,你应该这样使用:

    Thread thread = new Thread(download);
    thread .Start(filename);

But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

但是你的“下载”方法仍然需要对象,而不是字符串作为参数。您可以在方法体中将其强制转换为字符串。

#3


20  

You want to use the ParameterizedThreadStart delegate for thread methods that take parameters. (Or none at all actually, and let the Thread constructor infer.)

您希望使用参数zedthreadstart委托来获取参数的线程方法。(实际上没有,让线程构造函数推断)

Example usage:

使用示例:

var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent

thread.Start(filename)

#4


4  

You could also delegate like so...

你也可以委托。

ThreadStart ts = delegate
{
      bool moreWork = DoWork("param1", "param2", "param3");
      if (moreWork) 
      {
          DoMoreWork("param1", "param2");
      }
};
new Thread(ts).Start();

#5


2  

You can encapsulate the thread function(download) and the needed parameter(s)(filename) in a class and use the ThreadStart delegate to execute the thread function.

您可以在类中封装线程函数(下载)和所需的参数(文件名),并使用ThreadStart委托执行线程函数。

public class Download
{
    string _filename;

    Download(string filename)
    {
       _filename = filename;
    }

    public void download(string filename)
    {
       //download code
    }
}

Download = new Download(filename);
Thread thread = new Thread(new ThreadStart(Download.download);

#6


1  

In Additional

在额外的

    Thread thread = new Thread(delegate() { download(i); });
    thread.Start();

#7


0  

How about this: (or is it ok to use like this?)

这个怎么样(或者这样使用可以吗?)

var test = "Hello";
new Thread(new ThreadStart(() =>
{
    try
    {
        //Staff to do
        Console.WriteLine(test);
    }
    catch (Exception ex)
    {
        throw;
    }
})).Start();

#8


0  

here is the perfect way...

这是最好的方法……

private void func_trd(String sender)
{

    try
    {
        imgh.LoadImages_R_Randomiz(this, "01", groupBox, randomizerB.Value); // normal code

        ThreadStart ts = delegate
        {
            ExecuteInForeground(sender);
        };

        Thread nt = new Thread(ts);
        nt.IsBackground = true;

        nt.Start();

    }
    catch (Exception)
    {

    }
}

private void ExecuteInForeground(string name)
{
     //whatever ur function
    MessageBox.Show(name);
}

#1


589  

The simplest is just

最简单的就是

string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();

The advantage(s) of this (over ParameterizedThreadStart) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object all the time.

这种方法的优点(优于参数化的threadstart)是可以传递多个参数,并且可以在编译时进行检查,而不需要一直从对象中强制转换。

#2


30  

Look at this example:

看看这个例子:

public void RunWorker()
{
    Thread newThread = new Thread(WorkerMethod);
    newThread.Start(ParameterObject);
}

public void WorkerMethod(object parameterObject)
{
    // do your job!
}

You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.

您首先通过将委托传递给worker方法来创建一个线程,然后用一个线程启动它。以对象为参数的Start方法。

So in your case you should use it like this:

所以在你的例子中,你应该这样使用:

    Thread thread = new Thread(download);
    thread .Start(filename);

But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

但是你的“下载”方法仍然需要对象,而不是字符串作为参数。您可以在方法体中将其强制转换为字符串。

#3


20  

You want to use the ParameterizedThreadStart delegate for thread methods that take parameters. (Or none at all actually, and let the Thread constructor infer.)

您希望使用参数zedthreadstart委托来获取参数的线程方法。(实际上没有,让线程构造函数推断)

Example usage:

使用示例:

var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent

thread.Start(filename)

#4


4  

You could also delegate like so...

你也可以委托。

ThreadStart ts = delegate
{
      bool moreWork = DoWork("param1", "param2", "param3");
      if (moreWork) 
      {
          DoMoreWork("param1", "param2");
      }
};
new Thread(ts).Start();

#5


2  

You can encapsulate the thread function(download) and the needed parameter(s)(filename) in a class and use the ThreadStart delegate to execute the thread function.

您可以在类中封装线程函数(下载)和所需的参数(文件名),并使用ThreadStart委托执行线程函数。

public class Download
{
    string _filename;

    Download(string filename)
    {
       _filename = filename;
    }

    public void download(string filename)
    {
       //download code
    }
}

Download = new Download(filename);
Thread thread = new Thread(new ThreadStart(Download.download);

#6


1  

In Additional

在额外的

    Thread thread = new Thread(delegate() { download(i); });
    thread.Start();

#7


0  

How about this: (or is it ok to use like this?)

这个怎么样(或者这样使用可以吗?)

var test = "Hello";
new Thread(new ThreadStart(() =>
{
    try
    {
        //Staff to do
        Console.WriteLine(test);
    }
    catch (Exception ex)
    {
        throw;
    }
})).Start();

#8


0  

here is the perfect way...

这是最好的方法……

private void func_trd(String sender)
{

    try
    {
        imgh.LoadImages_R_Randomiz(this, "01", groupBox, randomizerB.Value); // normal code

        ThreadStart ts = delegate
        {
            ExecuteInForeground(sender);
        };

        Thread nt = new Thread(ts);
        nt.IsBackground = true;

        nt.Start();

    }
    catch (Exception)
    {

    }
}

private void ExecuteInForeground(string name)
{
     //whatever ur function
    MessageBox.Show(name);
}