C# Call a method in a new thread

后端 未结 6 1279
甜味超标
甜味超标 2020-12-13 04:08

I am looking for a way to call a method on a new thread (using C#).

For instance, I would like to call SecondFoo() on a new thread. However, I would the

6条回答
  •  -上瘾入骨i
    2020-12-13 04:18

    If you actually start a new thread, that thread will terminate when the method finishes:

    Thread thread = new Thread(SecondFoo);
    thread.Start();
    

    Now SecondFoo will be called in the new thread, and the thread will terminate when it completes.

    Did you actually mean that you wanted the thread to terminate when the method in the calling thread completes?

    EDIT: Note that starting a thread is a reasonably expensive operation. Do you definitely need a brand new thread rather than using a threadpool thread? Consider using ThreadPool.QueueUserWorkItem or (preferrably, if you're using .NET 4) TaskFactory.StartNew.

提交回复
热议问题