Pass Parameters through ParameterizedThreadStart

前端 未结 7 1113
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 16:32

I\'m trying to pass parameters through the following:

Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));

Any idea how to do th

7条回答
  •  借酒劲吻你
    2021-01-30 16:51

    Use overloaded Thread.Start method, which accepts object (you can pass your custom type or array if you need several parameters):

    Foo parameter = // get parameter value
    Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));
    thread.Start(parameter);
    

    And in DoMethod simply cast argument to your parameter type:

    private void DoMethod(object obj)
    {
        Foo parameter = (Foo)obj;
        // ...    
    }
    

    BTW in .NET 4.0 and above you can use tasks (also be careful with race conditions):

    Task.Factory.StartNew(() => DoMethod(a, b, c));
    

提交回复
热议问题