I have a UnitOfWork class that commits or rolls back transactions depending on errors in the block.
class UnitOfWork: IDispose
{
public void Dispose()
{
if (Marshal.GetExceptionCode() == 0
|| Marshal.GetExceptionPointers() == IntPtr.Zero)
{
// Commit
}
else
{
// Rollback
}
}
}
}
This class is used in the following manner:
try
{
using (var uow = new UnitOfWork())
{
// Do something here that causes an exception
}
}
catch
{
using (var uow = new UnitOfWork())
{
// Log exception
}
}
I have gone through this article: Detecting a Dispose() from an exception inside using block
In the above question, Steven (one of the people who replied) mentions that if I detect an exception inside Dispose() for the "using" block from the "try" section, I can not create another UnitOfWork class in the "catch" block and log errors to the database (since the "Marshal" code in Dispose() will continue to say there is an exception), meaning the ExceptionCode and ExceptionPointers will "float" (?) from the try block to the catch block.
However, in my case, this works correctly - ie. if there is an exception in the "using (var uow = new UOW)" block in the "try" section, it correctly catches the exception and then in the catch block the "if" condition passes, causing a commit to happen and allowing me to log exceptions.
It boils down to me having an incomplete understanding of how Marshal.GetExceptionPointers() work. Can someone please confirm if my usage pattern will work correctly (so far all tests seem to show that it works correctly) and what exactly is Marshal.GetExceptionPointers() doing?