I'm using this class to prevent two application (one windows application and one web application running on the same OS) using a shared file at the same time. But I get the error "Object synchronization method was called from an unsynchronized block of code."
class SharedMutex : IDisposable
{
readonly Mutex mutex;
/// <summary>
/// This function will wait if other thread has owned the mutex
/// </summary>
/// <param name="name"></param>
public SharedMutex(string name)
{
bool m = Mutex.TryOpenExisting(name, out mutex);
if (m)
{
mutex.WaitOne();
}
else
{
mutex = new Mutex(true, name);
}
}
public const string Logs = @"Global\Logs";
public void Dispose()
{
mutex.ReleaseMutex();
mutex.Dispose();
}
}
And this is the way I'm using this class
using (new SharedMutex(SharedMutex.Logs))
{
///access the shared file
}
This class exists in both projects.
Note: I am not looking for a solution to the problem to access the files, I need to know why my code has problem. Because I want to use this code for other purposes also. Thank you.