thread with multiple parameters

前端 未结 11 1444
一生所求
一生所求 2020-11-29 04:16

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

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

Here is wh

相关标签:
11条回答
  • 2020-11-29 05:07

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

    public void StartThread()
    {
        // ...
        Thread standardTCPServerThread = new Thread(
            () => standardServerThread.Start(/* whatever arguments */));
    
        standardTCPServerThread.Start();
    }
    
    0 讨论(0)
  • 2020-11-29 05:08

    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.

    0 讨论(0)
  • 2020-11-29 05:10

    You need to pass a single object, but if it's too much hassle to define your own object for a single use, you can use a Tuple.

    0 讨论(0)
  • 2020-11-29 05:12

    Try using a lambda expression to capture the arguments.

    Thread standardTCPServerThread = 
      new Thread(
        unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
      );
    
    0 讨论(0)
  • 2020-11-29 05:14

    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 
       }
    }
    
    0 讨论(0)
提交回复
热议问题