Reputation: 2122
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:
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.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
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:
Upvotes: 1