I'm trying to use C# mutex to ensure my application is running in single instance. So, the application is acquiring global mutex on start, and releasing it on exit. If the mutex acquisition is failed, the error is shown. The application is a console app and it's mostly asynchronous (Main method is async). Basically, the mutex is acquired at the beginning of Main method, and released at the end of it. The problem is that the Main method being asynchronous, its ending may be executed on a different thread than the beginning. So, when I try to release the mutex, I get "Object synchronization method was called from an unsynchronized block of code" exception because the mutex cannot be released from another thread. But I don't use the mutex for inter-thread synchronyzation, I use it for inter-process synchronization. So I don't really care which thread releases the mutex since it's guaranteed that acquire and release are not conflicting with each other. I know there are two ways to avoid this error:
- Use separate thread for mutex (this thread will acquire the mutex, then block and wait for application to exit, then release the mutex)
- Use main thread with synchronization context, which will allow to run await continuations on the same thread
Both of these ways seem too cumbersome. Is there a better way to ensure single instance for async app?