我正在使用此类来防止两个应用程序(一个Windows应用程序和一个在同一OS上运行的Web应用程序)同时使用共享文件。但是我收到错误消息“从未同步的代码块调用了对象同步方法。”
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();
}
}
这就是我使用此类的方式
using (new SharedMutex(SharedMutex.Logs))
{
///access the shared file
}
两个项目中都存在此类。
注意:我不是在寻找访问文件问题的解决方案,我需要知道为什么我的代码有问题。因为我也想将此代码用于其他目的。 谢谢。