c#文件读/写锁定
本文关键字:写锁 锁定 文件 | 更新日期: 2023-09-27 18:19:29
我使用StreamReader
在两个线程中读取/写入文件,一个线程读取,另一个线程写入。我希望这两件事不要同时发生。我应该用什么锁?我看了一些例子,但他们使用的是FileStream.Lock
,我不确定我是否可以将其与StreamReader
一起使用,所以请澄清。
您可以使用信号量
http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx
除了锁定文件本身之外,还可以使用"lock"关键字。否则,您将在尝试使用锁定文件时抛出异常
private object lockObject = new Object();
// Code in thread that reads
lock(lockObject)
{
// Open the file and do something
// Be sure to close it when done.
}
// Somewhere else in another thread
lock(lockObject)
{
// Open the file for writing and do somethign with it
// Be sure to close it when done.
}
您可以创建自己的锁:
class Example
{
private static readonly object SyncRoot = new object();
void ReadOrWrite()
{
lock(SyncRoot)
{
// Perform a read or write
}
}
}