Advantage of using Thread.Start vs QueueUserWorkItem

后端 未结 9 1613
有刺的猬
有刺的猬 2020-11-28 12:49

In multithreaded .NET programming, what are the decision criteria for using ThreadPool.QueueUserWorkItem versus starting my own thread via new Thread() and Thread.Start()?

9条回答
  •  旧巷少年郎
    2020-11-28 12:59

    If you're creating your own threads, it makes sense to start them on first use and then let them hang around for a while in case you need them again - you make an idle thread wait on an event so you can reactivate it by signaling the event, and after a long enough time elapses, the thread will wake itself and exit, reclaiming the unused resources. By keeping a small number of idle threads ready to be reused, you reduce the overhead of constantly creating and destroying threads (which is significant for sufficiently short-lived operations).

    But this is basically what the thread queue already does for you - so you may as well use it. It's a solved problem.

    A similar debate used to happen in the C++ community about strings, believe it or not. Should we each write our own string class, or should we use std::string? The answer depends on whether you want to learn how to write a string class, or you're done with that and you want to get on with inventing something new.

提交回复
热议问题