ThreadStates and Services

UncleRonin

Well-known member
Joined
Feb 28, 2006
Messages
230
Location
South Africa
Programming Experience
5-10
Can someone help explain to me the way Services and Threading works in this situation...

I have a service which OnStart() creates background threads. It uses a global variable Active As Boolean to track whether or not threads can execute. OnStart() Active = True and OnStop() Active = False. In the threads there are the following execution patterns...
VB.NET:
'Pattern A
While Me.Active
    Thread.Sleep(1000)
    DoStuff()
    DoOtherStuff()
End While

VB.NET:
'Pattern B
While Me.Active
    DoStuff()
    Thread.Sleep(1000)
    DoOtherStuff()
End While

In Pattern A if the service is stopped (Active = False) all the code executes normally and the thread loop exits like you'd expect. But if the service is stopped then Pattern B will execute DoStuff() but halts. Nothing else happens after Thread.Sleep() so DoOtherStuff() is never called. Is this the way it's supposed to happen or is something funky going on?

Just because the service is stopping surely the thread won't as well, at least not until it's duties are performed. No errors are thrown so it's really quite confusing. I was wondering if maybe the ThreadState WaitSleepJoin had something to do with this behaviour but I'm not knowledgable enough on the subject to comment. What do you think?
 
Background threads (IsBackground=True thread, BackgroundWorker, threadpool threads) are aborted immediately if main thread stops. To synchronize thread work that need to finish on stop you can use wait handles, for example this post touches the subject using a ManualResetEvent: http://www.vbdotnetforums.com/showpost.php?p=75245&postcount=7
 
Okay, that's weird. Each time I've tested I've never gotten a thread abort exception anywhere. EDIT: I've never gotten any exceptions actually even when encapsulating all thread code in a catch statement.

Also in my OnStop() I wait until the thread count is 0 so all threads can finish executing and only once they're all done will OnStop() finish. Then the aborts will be handled, etc, surely? In all the tests I've done using Pattern B DoOtherStuff() always completes properly and if I have additional methods or calls they complete as well. It's just with Pattern A that the service gives me the finger *falls over*
 
Back
Top