Cristiano Ghersi
Cristiano Ghersi

Reputation: 2122

UWP Ideal number of threads

I have a UWP app that spawns a few threads in background to perform low-priority activities.

I measured the amount of threads that the app is using, and I have seen 48 threads: 16 threads are created by my code, and 32 are unknown, probably created by the UWP framework.

In general, the threads created by my code have two possible behaviors:

  1. there is a blocking queue and the main thread method is most of the time blocked on the Take() from that queue. An agent that wants to enqueue a task can just Enqueue() a state object that is passed to the main thread method via this queue.
  2. there is a simple boolean flag runTask that is set to true when an agent wants the background activity to execute, and the main thread method is in an infinite loop, which checks the runTask variable: if it is false it Sleeps for 300 milliseconds, otherwise it executes the activity and sets the runTask variable to false.

EDIT: I changed the boolean flag into a ManualResetEvent following the suggestions in the comments and answers.

Now, are 48 threads too many?

Should I reduce them?

And if yes, is there a way to tell the UWP framework to use less threads?

I would like to avoid my app to spend too much time in thread context switching and rather use this time for actual computation!

Please let me know your thoughts.

Upvotes: 1

Views: 123

Answers (1)

JonasH
JonasH

Reputation: 36371

Now, are 48 threads too many? Should I reduce them?

There are a general recommendation to limit the number of threads to use. One reason for this is that each thread needs some memory for the stack and other bookkeeping. There can also be problems when using the threadpool since it limits the rate for creating new threads.

48 threads might be a bit higher than normal, but is probably not excessive. It would be up to you to if you want to spend the time to improve this or not.

there is a simple boolean flag runTask that is set to true when an agent wants the background activity to execute, and the main thread method is in an infinite loop, which checks the runTask variable: if it is false it Sleeps for 300 milliseconds, otherwise it executes the activity and sets the runTask variable to false.

This is probably not the best way to do it, there are better alternatives:

  • A timer for things that should be run periodically.
  • Just running tasks on the threadpool when needed, using a limitedconcurrencyTaskScheduler if you need to ensure exclusive access to some resource.
  • A manualResetEvent or semaphore to block a thread until another thread unblocks it. The later supports waiting asynchronously.

Upvotes: 1

Related Questions