C# 多参数线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/831009/
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-05 03:22:57  来源:igfitidea点击:

thread with multiple parameters

c#.netmultithreadingparametersthread-safety

提问by Lucas B

Does anyone know how to pass multiple parameters into a Thread.Start routine?

有谁知道如何将多个参数传递到 Thread.Start 例程中?

I thought of extending the class, but the C# Thread class is sealed.

我想过扩展类,但是C# Thread 类是密封的。

Here is what I think the code would look like:

这是我认为代码的样子:

...
    Thread standardTCPServerThread = new Thread(startSocketServerAsThread);

    standardServerThread.Start( orchestrator, initializeMemberBalance, arg, 60000);
...
}

static void startSocketServerAsThread(ServiceOrchestrator orchestrator, List<int> memberBalances, string arg, int port)
{
  startSocketServer(orchestrator, memberBalances, arg, port);
}

BTW, I start a number of threads with different orchestrators, balances and ports. Please consider thread safety also.

顺便说一句,我用不同的编排器、余额和端口启动了许多线程。还请考虑线程安全。

采纳答案by JaredPar

Try using a lambda expression to capture the arguments.

尝试使用 lambda 表达式来捕获参数。

Thread standardTCPServerThread = 
  new Thread(
    unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
  );

回答by Reed Copsey

You need to wrap them into a single object.

您需要将它们包装成一个对象。

Making a custom class to pass in your parameters is one option. You can also use an array or list of objects, and set all of your parameters in that.

制作一个自定义类来传递您的参数是一种选择。您还可以使用数组或对象列表,并在其中设置所有参数。

回答by Kamarey

You can't. Create an object that contain params you need, and pass is it. In the thread function cast the object back to its type.

你不能。创建一个包含您需要的参数的对象,并传递它。在线程函数中,将对象转换回其类型。

回答by Syed Tayyab Ali

You can take Object array and pass it in the thread. Pass

您可以获取 Object 数组并将其传递到线程中。经过

System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 

Into thread constructor.

进入线程构造函数。

yourFunctionAddressWhichContailMultipleParameters(object[])

You already set all the value in objArray.

您已经在 objArray 中设置了所有值。

you need to abcThread.Start(objectArray)

你需要 abcThread.Start(objectArray)

回答by mqp

You could curry the "work" function with a lambda expression:

您可以使用 lambda 表达式咖喱“工作”函数:

public void StartThread()
{
    // ...
    Thread standardTCPServerThread = new Thread(
        () => standardServerThread.Start(/* whatever arguments */));

    standardTCPServerThread.Start();
}

回答by Frederik Gheysels

Use the 'Task' pattern:

使用“任务”模式:

public class MyTask
{
   string _a;
   int _b;
   int _c;
   float _d;

   public event EventHandler Finished;

   public MyTask( string a, int b, int c, float d )
   {
      _a = a;
      _b = b;
      _c = c;
      _d = d;
   }

   public void DoWork()
   {
       Thread t = new Thread(new ThreadStart(DoWorkCore));
       t.Start();
   }

   private void DoWorkCore()
   {
      // do some stuff
      OnFinished();
   }

   protected virtual void OnFinished()
   {
      // raise finished in a threadsafe way 
   }
}

回答by Opus

Here is a bit of code that uses the object array approach mentioned here a couple times.

这是一些使用这里提到的对象数组方法的代码。

    ...
    string p1 = "Yada yada.";
    long p2 = 4715821396025;
    int p3 = 4096;
    object args = new object[3] { p1, p2, p3 };
    Thread b1 = new Thread(new ParameterizedThreadStart(worker));
    b1.Start(args);
    ...
    private void worker(object args)
    {
      Array argArray = new object[3];
      argArray = (Array)args;
      string p1 = (string)argArray.GetValue(0);
      long p2 = (long)argArray.GetValue(1);
      int p3 = (int)argArray.GetValue(2);
      ...
    }>

回答by Aaron P. Olds

.NET 2 conversion of JaredPar answer

JaredPar 答案的 .NET 2 转换

Thread standardTCPServerThread = new Thread(delegate (object unused) {
        startSocketServerAsThread(initializeMemberBalance, arg, 60000);
    });

回答by Marek Bar

I've been reading yours forum to find out how to do it and I did it in that way - might be useful for somebody. I pass arguments in constructor which creates for me working thread in which will be executed my method - execute()method.

我一直在阅读您的论坛以了解如何做到这一点,我就是这样做的 - 可能对某些人有用。我在构造函数中传递参数,该构造函数为我创建工作线程,将在其中执行我的方法 - execute()方法。

 using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace Haart_Trainer_App

{
    class ProcessRunner
    {
        private string process = "";
        private string args = "";
        private ListBox output = null;
        private Thread t = null;

    public ProcessRunner(string process, string args, ref ListBox output)
    {
        this.process = process;
        this.args = args;
        this.output = output;
        t = new Thread(new ThreadStart(this.execute));
        t.Start();

    }
    private void execute()
    {
        Process proc = new Process();
        proc.StartInfo.FileName = process;
        proc.StartInfo.Arguments = args;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start();
        string outmsg;
        try
        {
            StreamReader read = proc.StandardOutput;

        while ((outmsg = read.ReadLine()) != null)
        {

                lock (output)
                {
                    output.Items.Add(outmsg);
                }

        }
        }
        catch (Exception e) 
        {
            lock (output)
            {
                output.Items.Add(e.Message);
            }
        }
        proc.WaitForExit();
        var exitCode = proc.ExitCode;
        proc.Close();

    }
}
}

回答by Muhammad Mubashir

void RunFromHere()
{
    string param1 = "hello";
    int param2 = 42;

    Thread thread = new Thread(delegate()
    {
        MyParametrizedMethod(param1,param2);
    });
    thread.Start();
}

void MyParametrizedMethod(string p,int i)
{
// some code.
}