I have a WPF-application that uses several background threads for precompiling LINQ-queries and precaching some values, that will be needed later. TPL is used to start these tasks by:
var newTask = new Task(taskAction, myCancelToken, TaskCreationOptions.LongRunning);
newTask.Start();
This works, the tasks are distributed over several cpu cores etc. However, these threads cause a high cpu load, that is perceptible in the UI, which tends to stumble or even freeze, as long as threads aren’t finished.
So, what could be a reasonable way to smoothen UI. By researching I found, that one’s not supposed to give threads special priorities. Others mean, frequent use of Thread.Sleep() was the way to go, which seems a bit outworn and hacky to me.
Are there additional ways I’m not aware of? Are there real disadvantages of priorizing threads (which isn’t possible via TPL directly, afaik)?
Thanks in advance!
10 threads is too many on say a 4-core machine. If they are compute-bound like pre-compiling queries, they will all be contesting for cpu time and will make the whole machine unresponsive.
I suggest you use
Environment.ProcessorCountto find out how many cores are available, and only start ( that number – 1 ) threads at a time. You can prioritise which work runs first and queue the others as continuations.This will leave a core free to service your UI thread and should make the app responsive again.