2

I am refactoring my Windows Service so that access to the named Mutex is centralized in the worker thread's method. Instead of releasing it in OnStop() and ~DerivedService() it now should be released in the finally block.

I've observed skipping of destructor calls when I hit Shift+F5 to stop debugging and expect that and a crash (more serious than politely raising an exception) would be the only reasons to skip the finally block.

As I am coding a Service and its worker thread I was hoping to clear up any nasty surprises here before the rigmorale of replacing service code, logging in and out, attaching debugger etc.

Thanks.

John
  • 6,433
  • 7
  • 47
  • 82

2 Answers2

2

There is a built in mechanism in the Windows Mutexes to handle the situation where a program or thread ended unexpectedly, without releasing the mutex. If the thread currently holding the mutex quits, the mutex will become unlocked automatically, but in a special abandoned state.

Instead of focusing too much on cleaning up, make a special routine whenever the mutex is acquired and its state is abandoned. In that case you should probably do some extra consistency checks on the protected resource - it could have been left in any state.

Anders Abel
  • 67,989
  • 17
  • 150
  • 217
  • I am very new to Windows Threads and the project(s) and data aren't too complicated. I've only just realised that the error about sync'ing from an unsync'ed block of code refers to the thread-local (as the MSDN puts it) nature of mutex locking and so am really just looking for a better place for my cleanup code. Not that I ever got to fully understand all the events that can fire at a service. – John Oct 23 '11 at 18:56
  • I had been expecting `AbandonedMutexExceptions` but when I stepped into it I found I was getting that "sync'ing from an unsync'ed block of code" error I mentioned. – John Oct 23 '11 at 19:19
1

There are many (in reality a few) reasons why a final block won't execute. In general if you call Environment.FailFast, some asynchronous exceptions (StackOverflowException, ExecutingEngineException), shutting down violently your PC :-), and (often forgotten) if there is an exception in a finalizer method

Read for example here Does the C# "finally" block ALWAYS execute? and In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown?

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280