c# thread method

前端 未结 5 1202
太阳男子
太阳男子 2020-12-10 02:02

If I have a

public void Method(int m)
{
  ...
}

how can I create a thread to this method?

Thread t = new Thread((Me

相关标签:
5条回答
  • 2020-12-10 02:43

    please try:

    Thread t = new Thread(new ThreadStart(method)); 
    t.Start();
    
    0 讨论(0)
  • 2020-12-10 02:48

    You can do this using a lambda expression. The C# compiler automatically creates the ThreadStart delegate behind the scenes.

    Thread t = new Thread(() => Method(m));
    t.Start();
    

    Note that if you change m later in your code, the changes will propagate into the thread if it hasn't entered Method yet. If this is a problem, you should make a copy of m.

    0 讨论(0)
  • 2020-12-10 02:51

    Method needs to take an object not an int to be able to use the ParameterizedThreadStart delegate.

    So change m to an object and cast it to an int first off.

    0 讨论(0)
  • 2020-12-10 02:53

    The method you are calling requires a parameter. Because it has one parameter and a return type of void you can use the following

    ThreadPool.QueueUserWorkItem(o => Method(m));
    

    You do not need to change the int to an object in the method signature using this method.

    There are advantages to using the ThreadPool over starting your own Thread manually. Thread vs ThreadPool

    0 讨论(0)
  • 2020-12-10 03:01
    ThreadStart tsd = new ThreadStart(ThreadMethod);
    Thread t = new Thread(tsd);
    t.Start();
    

    Thread methods needs to be a method with return type void and accepting no argument.

    public void ThreadMethod() {.....}
    

    There is another variant which is ParameterizedThreadStart

    ParameterizedThreadStart ptsd = new ParameterizedThreadStart(ThreadParamMethod);
    Thread t = new Thread(ptsd);
    t.Start(yourIntegerValue);
    

    ThreadParamMethod is a method which return type is void and accept one argument of type object. However you can pass just about any thing as object.

    public void ThreadParamMethod(object arg) {.....}
    
    0 讨论(0)
提交回复
热议问题