Modern .NET threading patterns

Status
Not open for further replies.

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
I was looking at an old app I wrote in the .NET 2.0 (or maybe 1.1, I can't remember) I've updated it in 2008 with a WPF front end, but haven't done much with the back-end of it which uses some pretty mediocre multi-threading code. (FWIW, the old source code and compiled .exe are available off my blog in this .zip file.)

It was a basic Directory analyzer app I originally wrote as a teaching exercise for new devs to show them multi-threading. (It is just a classic multi-threaded, recursive tree-descent algorithm with the minor "twist" that it generates constant UI progress updates to the UI thread) However, reviewing it recently, two things became apparent:
1) I wasn't perfect in my understanding of multi-threading back then
2) The patterns available in .NET 4.0 to multi-thread have come a long way since then.
3) I could still stand to learn some new "best practices" for multi-threading.

So, I thought I'd post a challenge/conversation starter for guys to re-write the multi-threading bits in a "modern" way. (Either by posting pseudo-code or real code, whatever.) What techniques would you use? Any cool tricks/thoughts on how you would make it better? Places to Lock? Lock on what objects? Best ways to throttle the background stuff so the UI never gets sluggish or non-responsive? Cool ways to use new framework features to make the code more elegant?

General concepts used by code:
  • The XAML/WPF front-end is data-bound to a DirectoryStructure object
  • Each DirectorySize object, when instantiated, launches a background process to do the file searching work to determine the size of the files in the directory and generates DirectoryStructure objects for each subdirectory. (Which, in turn generate their own background processes, recursively.)
  • Background threads cannot directly interact with the UI thread, or the dataobjects owned by the UI thread. (IOW, UI stuff must be invoked via the Dispatcher object.)
  • The algorithm must keep the UI reasonably responsive, and must not cause resource starvation, stack overflows or any other nasty multi-threaded bugs.
  • WPF databinding engine requires that the data-objects fire PropertyChanged events to inform the UI of its need to update itself for new values. If PropertyChanged events aren't fired when values change, the UI may not correctly update itself.
  • A parent thread will typically finish its work before its children will finish theirs, but the parent's data will not be correct until the children finish their work. Somehow, upon completion of a parent's work, its thread must yield to other threads while waiting for children to complete. (IOW, since the app will probably launch more threads than it can simultaneously work on, you can't have an "active" thread polling for other threads to complete, because the threads that need to complete, quite possibly be waiting for the parent threads to yield before they start.) But, after its children complete, the parent thread must be active long enough to compute its final values and send PropertyChanged events to the UI
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
To possibly jump start the conversation, I think there are three main issues (maybe more) this logic problem gets us.
1) What is the "best" modern background threading pattern for things that you fully expect to saturate your resources while keeping the UI responsive? IOW, how do you implement throttling so that the UI stays responsive in these scenarios.
2) If a thread needs to wait for a bit (say to poll for the result of another thread), what is the most elegant way to do this without blocking any resources from an abundance of other threads who are eager to use them? (In the past, I've used timers and events, but that seems rather klunky to do it that way.)
3) Since, often we are limited to a single UI thread that many operations have to occur on, are their rules to follow to prevent this from becoming a blocker or a bottleneck?
 

Horatio

Ars Legatus Legionis
24,430
Moderator
1) What is the "best" modern background threading pattern for things that you fully expect to saturate your resources while keeping the UI responsive? IOW, how do you implement throttling so that the UI stays responsive in these scenarios.
I've never needed to do this. The OS will schedule things so that background threads won't hurt the responsiveness of the UI thread in general. So long as you do your work on the worker thread, everyhing should be fine.
2) If a thread needs to wait for a bit (say to poll for the result of another thread), what is the most elegant way to do this without blocking any resources from an abundance of other threads who are eager to use them? (In the past, I've used timers and events, but that seems rather klunky to do it that way.)
Use Events since they will yield the thread back to the threadpool. They may be a little clunky, but they are efficient. The alternative is to use the .NET Async pattern (BeginXXX/EndXXX).
3) Since, often we are limited to a single UI thread that many operations have to occur on, are their rules to follow to prevent this from becoming a blocker or a bottleneck?
WPF supports multiple UI threads :) General advice is to have the minimum amount of processing in your ViewModel/View. Anything heavyweight should happen off-thread if you can, and only update the UI with the results on the UI thread. Rx can help there.
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Horatio":31wo5s8b said:
The OS will schedule things so that background threads won't hurt the responsiveness of the UI thread in general. So long as you do your work on the worker thread, everyhing should be fine.
Sure, but what is the best way to do this? BackgroundWorker objects? Task objects? The Parallel class (obviously doesn't make sense here, but could be used in other multi-threading stuff)?
Horatio":31wo5s8b said:
Use Events since they will yield the thread back to the threadpool.
How are you suggesting we use events for polling? Timers? If so, don't they consume a lot of stack resources and increase the likelihood of a stack overflow? (I could be wrong here.)
Horatio":31wo5s8b said:
Rx can help there.
I watched that whole video, and never saw anything I thought was applicable to WPF apps. (It appeared to be web/Silverlight based and designed for that environment) What was I missing?
 

Horatio

Ars Legatus Legionis
24,430
Moderator
Sure, but what is the best way to do this? BackgroundWorker objects? Task objects? The Parallel class (obviously doesn't make sense here, but could be used in other multi-threading stuff)?
I like ThreadPool.QueueUserWorkItem, and I've often used Timers to do background operations on a schedule. Heck, Delegate.BeginInvoke is often a convenient way to execute something on a threadpool thread. I've used BackgroundWorker a little, but I don't really like it. Not for any good reason though.
How are you suggesting we use events for polling? Timers? If so, don't they consume a lot of stack resources and increase the likelihood of a stack overflow? (I could be wrong here.)
First up, determine whether you need to poll, or you if you could do something Observable instead. If you do need to poll, yeah, use a timer. They use a handle, and need a threadpool thread, but otherwise, they don't use particularly much in the way of resources. I usually heap allocate my timers, so they don't take up stack space. Typically, I'll have only 1 timer driving all polling operations.
I watched that whole video, and never saw anything I thought was applicable to WPF apps. (It appeared to be web/Silverlight based and designed for that environment) What was I missing?
You're missing binding to Observable objects. If you bind an ItemsControl to an ObservableCollection, as the collection change, the view will automatically update. Now, couple that with Rx's ability to bind to a LINQ query and post items back to the UI thread, your UI only needs to do collection changes and repaints on the UI thread, leaving the heavy lifting to wherever you defined your LINQ expression.
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Horatio":2avrx26h said:
I usually heap allocate my timers, so they don't take up stack space. Typically, I'll have only 1 timer driving all polling operations.
Not sure I'm following you here. What are you doing to heap allocate them, and what code pattern are you using to allow numerous objects in different threads to share a single timer for their polling?
Horatio":2avrx26h said:
You're missing binding to Observable objects. If you bind an ItemsControl to an ObservableCollection, as the collection change, the view will automatically update.
I'm already doing all of that without any need for the Rx framework. The parts I've had to fire PropertyChanged events for are for the properties of the objects, not the object collections. Rx doesn't help at all with basic implementation of INotifyPropertyChanged, at least as far as I can see.
 

TheBorg

Ars Tribunus Angusticlavius
8,555
Horatio":reord4p7 said:
I've used BackgroundWorker a little, but I don't really like it. Not for any good reason though.
I've used BackgroundWorker and I like it over roll-your-own threadsing, primarily because it provides all the basic functionality you need without letting you get into too much trouble with subtle design flaws or performance overhead. That can be an important feature in a multideveloper environment with varying skillsets. Between BackgroundWorker, Timer and Events things are pretty much covered.

I also played around a bit with Concurrency and Coordination Runtime. Most of it through was fooling around with Microsoft Robotics Studio to interface with Mindstorms NXT, but it's usable in other concurrency applications.

The new Task Parallel Library in .NET 4 is something I haven't touched yet - anyone have any experience with it?
 

Horatio

Ars Legatus Legionis
24,430
Moderator
Not sure I'm following you here. What are you doing to heap allocate them, and what code pattern are you using to allow numerous objects in different threads to share a single timer for their polling?
I (where possible) try to use a single timer, then dispatch to new threads via QueueUserWorkItem. In your scenario though, where a parent thread scatters processing out to children, I would use events and WaitHandle.WaitAll so no polling happens at all.
I'm already doing all of that without any need for the Rx framework. The parts I've had to fire PropertyChanged events for are for the properties of the objects, not the object collections. Rx doesn't help at all with basic implementation of INotifyPropertyChanged, at least as far as I can see.
Yeah, Rx doesn't help with the basics, but it makes building bound collections easier.
 

Seltsam

Ars Tribunus Militum
2,881
The new Task Parallel Library in .NET 4 is something I haven't touched yet - anyone have any experience with it?

Yes, I've used it quite a bit in production code.

I (where possible) try to use a single timer, then dispatch to new threads via QueueUserWorkItem. In your scenario though, where a parent thread scatters processing out to children, I would use events and WaitHandle.WaitAll so no polling happens at all.

I'd use Task.Factory.StartNew() with the attach to parent option on child tasks (if you're targeting .NET 4).
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Horatio":18hk6e96 said:
In your scenario though, where a parent thread scatters processing out to children, I would use events and WaitHandle.WaitAll so no polling happens at all.
The problem with this is that it is doomed to eventually clog up whatever mechanism you are using to limit the number of concurrent threads. WaitHandle.WaitAll causes the thread to stay alive, and thus not return its resources back to the system for other threads to use. For this bit of sample code, it works for a bit until so many threads start that parents will wait forever for the children to complete, because the children can't get resources to run, since the parents haven't released them.

Seltsam,
I haven't tried Task.Factory.StartNew() with the attach to parent option on child tasks. I'll give it a whirl and see how it turns out.

BTW, is anyone else here playing with the source code I posted to see first hand some of the weird issues that pop up on multi-threaded tree traversing on a large tree?
 

Horatio

Ars Legatus Legionis
24,430
Moderator
The problem with this is that it is doomed to eventually clog up whatever mechanism you are using to limit the number of concurrent threads. WaitHandle.WaitAll causes the thread to stay alive, and thus not return its resources back to the system for other threads to use. For this bit of sample code, it works for a bit until so many threads start that parents will wait forever for the children to complete, because the children can't get resources to run, since the parents haven't released them.
How are you starting more threads than the threadpool allows? Are you using QueueUserWorkItem (I can't look at your code at work)?
 

TheJet

Ars Praefectus
4,598
Subscriptor++
Just out of curiosity, why not just have a set number of threads and dump your directories to be searched into a Queue for processing? The child items could notify the parent when their processing is complete, which could notify up the tree until the UI is complete...

** EDIT: It looks like you're taking your current approach simply to demonstrate thread interactions, so I'm assuming new algorithms to solve the problem with fewer/fixed numbers of threads is irrelevant :)
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Horatio":2qzgq8sb said:
The problem with this is that it is doomed to eventually clog up whatever mechanism you are using to limit the number of concurrent threads. WaitHandle.WaitAll causes the thread to stay alive, and thus not return its resources back to the system for other threads to use. For this bit of sample code, it works for a bit until so many threads start that parents will wait forever for the children to complete, because the children can't get resources to run, since the parents haven't released them.
How are you starting more threads than the threadpool allows? Are you using QueueUserWorkItem (I can't look at your code at work)?
I've done it with several techniques all the way from creating and launching new Thread objects to BackgroundWorker objects, etc. Since this learning code for me, I've changed it numerous times and tried numerous ways to do it.

Starting more threads than the thread pool allows is pretty trivially easy when you are descending a large tree and creating a thread for each node. IMO, in a perfect world, any/all activities that can be broken down into thread-able chunks and sent off to magical parallel-processing land should be threaded and allowed to utilize how-ever many CPUs/Cores are available to the code.
 

Horatio

Ars Legatus Legionis
24,430
Moderator
IMO, in a perfect world, any/all activities that can be broken down into thread-able chunks and sent off to magical parallel-processing land should be threaded and allowed to utilize how-ever many CPUs/Cores are available to the code.
Sure, but that's how the QueueUserWorkItem works - you post work to the queue, and as threadpool threads become available, your work items are serviced.
 

fitten

Ars Legatus Legionis
55,634
Subscriptor++
I've used ThreadPool in .NET 3.5 and earlier. I had to roll my own waiting, though. The problem with the threadpool comes if you have one thread dependent upon another thread (and so on) completing. The ThreadPool may not schedule them the way you want and you'll get a deadlock with all threads busy waiting on thread(s) that are yet to be scheduled. However, in one section of code, I've queued easily several thousand work items simultaneously (they were all independent of each other) and it work wonderfully. The great thing about it is that when running on a single cpu, dual cpu, quad, etc. it will expand the number of simultaneously running threads and make the best use of your machine without your having to do anything to get it (don't need to query the number of CPUs or anything) obviously.

Also, I like setting my work items to background (when appropriate, as it was in the above code) for the main benefit of process control. Background threads mostly mean they all die when the main thread exits. Otherwise, if your main exits but there are other threads running, your process won't go away until the other foreground threads also exit.
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Horatio":boh4x447 said:
IMO, in a perfect world, any/all activities that can be broken down into thread-able chunks and sent off to magical parallel-processing land should be threaded and allowed to utilize how-ever many CPUs/Cores are available to the code.
Sure, but that's how the QueueUserWorkItem works - you post work to the queue, and as threadpool threads become available, your work items are serviced.
But, your missing the issue here. If you do a .WaitAll for children to complete, eventually all available threads are filled with threads waiting for work to be done on threads that can't start until one of the waiting threads complete, and thus your app deadlocks. In this scenario, you have to release the parent's thread resources so that children can use them to do work.

EDIT: Fitten already said this, whoops . . .
 
Status
Not open for further replies.