我有多个asp.net网络应用程序服务于一组文件.在提供文件之前,会定期更新文件,但如果文件正在使用,则无法更新文件.
我可以通过使用命名的互斥锁解决此问题,其中名称是文件路径(当然替换无效字符).我在其他情况下使用过这个,但你可以看到效率低下.一次只能有一个进程提供文件.
读取器/写入器锁是完美的,但它们被设计为在单个进程中工作.另外,我必须为每个可能更新的文件创建一个读取器/写入器锁,并且有很多.
我真正需要的是一个可以像互斥锁一样命名的读/写锁.有这样的事吗?或者可以使用现有的锁创建这样的东西?
Jim*_*hel 19
可以使用Mutex和Semaphore模拟读/写锁.如果我每秒必须访问它数千次,我不会这样做,但是每秒数十次或者数百次,它应该可以正常工作.
这个锁允许1个写入者独占访问或N个(可能很大,但你必须定义它)读者的并发访问.
这是它的工作原理.我将以10个读者为例.
初始化一个名为Mutex,最初没有信号,一个名为Semaphore的10个插槽:
Mutex m = new Mutex(false, "MyMutex");
Semaphore s = new Semaphore(10, 10, "MySemaphore");
Run Code Online (Sandbox Code Playgroud)
获取读卡器锁:
// Lock access to the semaphore.
m.WaitOne();
// Wait for a semaphore slot.
s.WaitOne();
// Release mutex so others can access the semaphore.
m.ReleaseMutex();
Run Code Online (Sandbox Code Playgroud)
释放读卡器锁:
s.Release();
Run Code Online (Sandbox Code Playgroud)
获取作家锁:
// Lock access to the seamphore
m.WaitOne();
// Here we're waiting for the semaphore to get full,
// meaning that there aren't any more readers accessing.
// The only way to get the count is to call Release.
// So we wait, then immediately release.
// Release returns the previous count.
// Since we know that access to the semaphore is locked
// (i.e. nobody can get a slot), we know that when count
// goes to 9 (one less than the total possible), all the readers
// are done.
s.WaitOne();
int count = s.Release();
while (count != 9)
{
// sleep briefly so other processes get a chance.
// You might want to tweak this value. Sleep(1) might be okay.
Thread.Sleep(10);
s.WaitOne();
count = s.Release();
}
// At this point, there are no more readers.
Run Code Online (Sandbox Code Playgroud)
发布作者锁:
m.ReleaseMutex();
Run Code Online (Sandbox Code Playgroud)
虽然脆弱(每个使用它的过程都有相同数量的信号量!),我认为它会做你想要的,只要你不要太努力.