Mutexes and cocoa-sharp

2 views
Skip to first unread message

Erik Renes

unread,
Jan 16, 2008, 9:35:54 AM1/16/08
to cocoa-sharp-dev
Hi Everyone,

I have been having problems when exiting mono applications by right-
clicking the dock icon and selecting 'quit'. I have been able to
isolate the problem to the combination of Cocoa.Application.Run and
using a Mutex. Below you can find the most trivial example I could
come up with.

When starting the application, a mutex is created to ensure this is
the first instance of the application. If it is the first instance, I
execute Cocoa.Application.Init() and Run(). After starting the
application, I open the dock menu and click 'Quit'. Now the
application hangs.

The "run ended", "Exception" and "finally" statements are never
reached.

Could anybody advise me on the steps to take to troubleshoot this
issue? I have tried --trace, but that gives an output of hundreds of
megabytes, so that it is rather unusable I find.

Best Regards,
Erik Renes

// --- EXAMPLE PROBLEMATIC CODE:
using System.Threading;
using System;
using Cocoa;

public class hello{
public static void Main(string[] args){
Mutex mtxMain = null;
try
{
bool bFirstInstance;
mtxMain = new Mutex(true, "Local\\testmutex", out
bFirstInstance);
// bFirstInstance = true; // This is to test what happens
without mutex
if (bFirstInstance)
{
Cocoa.Application.Init();
Cocoa.Application.Run();
Console.Write("run ended");
}
}
// other exceptions
catch (Exception e)
{
Console.WriteLine("Exception: ");
Console.WriteLine(e.ToString());
}
finally{
Console.Write("finally!");
}
}
}

// --- END EXAMPLE CODE

Erik Renes

unread,
Jan 16, 2008, 11:45:51 AM1/16/08
to cocoa-sharp-dev
Hi all,

I have read a bit of documentation, and I have solved the problem by
changing the approach I took for cleanup.

In the documentation for NSApplication.terminate:
http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/NSApplication/terminate:

I have found that control is never given back to the 'main' function
after terminating, so I created an event handler as suggested in the
documentation. Cocoa# syntax as reference to others:
[Export("applicationWillTerminate:")]
public void ApplicationWillTerminate(Cocoa.Notification not)
{
// Cleanup code here
}

It's rather different from the standard windows forms way of going
about, so it may be worth mentioning somewhere :)

Best Regards,
Erik Renes
Reply all
Reply to author
Forward
0 new messages