Saturday, February 19, 2005

.NET app - another running instance check and DTC exception

This error and its fix is weird and i am posting this to a miserable developer, who is still trying to crack this error in this scenario. It was a requirement is to allow only one instance of the batch app to run, hence the following code was copied from internet to check if another instance of application is running, and abort the current instance

Process [] aoRunningInstance = Process.GetProcessesByName(Constant.APPLICATION_NAME);
if (aoRunningInstance.Length > 1)
throw new ApplicationException("Another instance of app is running. Aborting current instance.");
aoRunningInstance = null;

Everything went fine; it found another instance and aborted, but weirdly in a scenario

//Create a new Transaction
//Open SQL connection inside the Transaction
//Open DB2 connection inside the Transaction

Line where i try to open DB2 connection, an exception is thrown >>>>> [IBM][CLI Driver] CLI0126E Operation invalid at this time. SQLSTATE=HY011

It was found that if we comment out another instance check code, the error is not happening. #@$@#$@!#. Wait, fix to this error is even weirder, we open and close the DB2 connection before this another instance check code and click the error vanishes in thin air.

I found a another way of to check another running instance of the app from Updater Application Block,

private Mutex _appStartMutex;
private readonly Guid _mutexGuid = new Guid( new byte[] { 0x5F, 0x4D, 0x69, 0x63, 0x68, 0x61, 0x65, 0x6C, 0x20, 0x53, 0x74, 0x75, 0x61, 0x72, 0x74, 0x5F });
bool isOwned = false;
_appStartMutex = new Mutex( true, System.Reflection.Assembly.GetExecutingAssembly().FullName + _mutexGuid.ToString(), out isOwned );
if ( !isOwned ){
throw new ApplicationException("Another instance of app is running. Aborting current instance.");

This will not alow the application to run even if its run with different executable name or from a different location. But has overhead of Mutex, not sure if this will fix this the above error.

It indeed fixes the above issue and after some thought i think it will be performance effective to have Mutex instead of pulling every process name that is running machine, i always see a 100% spike if i do this using task manager.

No comments: