代码之家  ›  专栏  ›  技术社区  ›  Lucas B

多参数线程

  •  34
  • Lucas B  · 技术社区  · 15 年前

    有人知道如何将多个参数传递到一个线程中吗?启动例程?

    我想扩展类,但C线程类是密封的。

    我想代码应该是这样的:

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

    顺便说一句,我用不同的协调器、平衡和端口启动了许多线程。请同时考虑螺纹安全。

    11 回复  |  直到 7 年前
        1
  •  60
  •   serhio    14 年前

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

    Thread standardTCPServerThread = 
      new Thread(
        unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
      );
    
        2
  •  12
  •   Hamed    12 年前

    这里有一些代码使用了这里提到的几次对象数组方法。

        ...
        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);
          ...
        }>
    
        3
  •  11
  •   Reed Copsey    15 年前

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

    让自定义类传入参数是一个选项。还可以使用对象数组或列表,并在其中设置所有参数。

        4
  •  7
  •   Frederik Gheysels    15 年前

    使用“任务”模式:

    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 
       }
    }
    
        5
  •  5
  •   Brian Gideon    14 年前

    .NET 2 jaredpar答案的转换

    Thread standardTCPServerThread = new Thread(delegate (object unused) {
            startSocketServerAsThread(initializeMemberBalance, arg, 60000);
        });
    
        6
  •  3
  •   Kamarey    15 年前

    你不能。创建一个包含你需要的参数的对象,传递就是它。在thread函数中,将对象强制转换回其类型。

        7
  •  2
  •   Andro Selva Anand Wadhwani    12 年前

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

     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();
    
        }
    }
    }
    
        8
  •  2
  •   Muhammad Mubashir    12 年前
    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.
    }
    
        9
  •  1
  •   Ali Hawk Rong    7 年前

    您可以获取对象数组并在线程中传递它。通过

    System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 
    

    进入线程构造函数。

    yourFunctionAddressWhichContailMultipleParameters(object[])
    

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

    你需要 abcThread.Start(objectArray)

        10
  •  0
  •   mqp    15 年前

    您可以用lambda表达式转换“work”函数:

    public void StartThread()
    {
        // ...
        Thread standardTCPServerThread = new Thread(
            () => standardServerThread.Start(/* whatever arguments */));
    
        standardTCPServerThread.Start();
    }
    
        11
  •  0
  •   mcmillab    10 年前

    您需要传递单个对象,但如果定义自己的对象以供单独使用太麻烦,则可以使用 元组 .