C# Exception cleanup resource management like C++?

M

Mike N

Coming from a C++ background, are destructors called for all local
objects after a C# exception?

C++:

myproc() {

CSingleLock protect(&m_myCritsec, FALSE);
if (!protect.Lock())
{
// Handle error
}

// more stuff that can throw an exception

}

.... You know that the critical section for 'protect' is released
properly because its destructor will be called regardless of an
exception.

If I understand C#, you could not develop a similarly functioning
CSingleLock class because the destructor is called only at some later
random point by the garbage collection. So to properly release
semaphores, etc, you must use a try...finally construct everywhere,
manually track everything that might have been locked/used and make
sure it is released?
 
S

Sean Hederman

You could use the lock statement, or, if the object implements IDisposable
you can use the using construct

C#:
myproc() {
lock(this) {
// Do stuff inside lock, exceptions will release the lock.
}
}
or:
myproc() {
using(new MySingleLock(args)) {
// Do stuff, MySingleLock.Dispose will be automatically called on
exception and exiting scope
}
}
 
M

Mike N

C#:
myproc() {
lock(this) {
// Do stuff inside lock, exceptions will release the lock.
}
}

Thanks! This one appears very useful!

or:
myproc() {
using(new MySingleLock(args)) {
// Do stuff, MySingleLock.Dispose will be automatically called on
exception and exiting scope
}
}

Thanks, this was a general solution I was looking for; I had skimmed
over the 'using' keyword, thinking it was namespace scope only.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top