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
}
}
"Mike N" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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?
>
|