Search code examples
c#multithreadingcompact-frameworkthreadpoolbarcode-scanner

Is ThreadPool worth it in this scenario?


I have a thread that I fire off every time the user scans a barcode.

Most of the time it is a fairly short running thread. But sometimes it can take a very long time (waiting on a invoke to the GUI thread).

I have read that it may be a good idea to use the ThreadPool for this rather than just creating my own thread for each scan.

But I have also read that if the ThreadPool runs out of threads then it will just wait until some other thread exits (not OK for what I am doing).

So, how likely is it that I am going to run out of threads? And is the benefit of the ThreadPool really worth it? (When I scan it does not seem to take too long for the scan to "run" the thread logic.)


Solution

  • It depends on what you mean by "a very long time" and how common that scenario is.

    The MSDN topic "The Managed Thread Pool" offers good guidelines for when not to use thread pool threads:

    There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:

    • You require a foreground thread.
    • You require a thread to have a particular priority.
    • You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting.
    • You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment.
    • You need to have a stable identity associated with the thread, or to dedicate a thread to a task.