Check C#threads

Asked

Viewed 460 times

1

I am trying to understand the code below, but without success. From what I’ve researched, GetMaxThreads returns maximum available threads and GetAvailableThreads what is available. In the case of the output below, there are no more threads available? What . Net C# does in this situation?

int threads;
int disponiveis;
int dummy;
long consultas = Interlocked.Read(ref _threads);

ThreadPool.GetMaxThreads(out threads, out dummy);
ThreadPool.GetAvailableThreads(out disponiveis, out dummy);

_gerenciador.Log(String.Format("Status dos threads: Consultas {0}, Threads: {1}, Disponíveis: {2}", consultas, threads, disponiveis));

Exit:

Status dos threads: Consultas 2, Threads: 1023, Disponíveis: 1020
  • What do you mean "no more threads available"? The output indicates that there are more than 1000 threads available for your application (1020).

  • That’s what I’m asking. I didn’t understand the code, so that’s the question.

  • 2

    The thread pool has 1023 threads in total. Your program is using 2 of them, and there are 1020 available for when you put a job in the queue (via ThreadPool.QueueUserWorkItem, for example).

  • @carlosfigueira is right, just a small correction - the program is using 3 (the main thread counts as a thread in use.)

1 answer

2


The indication of threads available does not mean that these threads were, in fact, created. The ThreadPool works with a maximum number of threads (possible to be configured), the method GetMaxThreads returns this number, while the GetAvailableThreads returns the number of threads available (Max - In Use).

If the threads run out, the ThreadPool await the completion of some thread in use, to reuse it for new work.

It is worth remembering that even if the ThreadPool is exhausted yet it is possible to create new threads "in hand": new Thread(Metodo).Start()

Only code snippets using the ThreadPool is that they will not have their tasks executed immediately.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.