编辑:运行更多测试(在单声道上),我不太确定这是最好的方法。
我没有设法使任何东西崩溃,但执行只是在 之后暂停Run()
几秒钟,然后返回给调用者。所以我怀疑这不是支持这个代码片段的好兆头。
话虽如此,经过测试的场景远非现实。
另一种选择是以FileShare.ReadWrite
模式打开文件,让操作系统关心锁定。
public void Run()
{
var file = @"/home/me/test.txt";
var threads = new Thread[3];
for (int i = 0; i < threads.Length; i++) {
int j = i;
threads[j] = new Thread( s => {
Console.WriteLine("thread " + j + " is running...");
using (var stream = File.Open(file, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.ReadWrite))
{
Console.WriteLine("thread " + j + " is holding the file!");
var data = ASCIIEncoding.ASCII.GetBytes("hello, I'm stream " + j);
stream.Write(data, 0, data.Length);
Thread.Sleep(1000);
}});
}
foreach (var t in threads)
t.Start();
foreach (var t in threads)
t.Join();
Console.WriteLine(File.ReadAllText(file));
}
输出:
thread 1 is running...
thread 0 is running...
thread 2 is running...
thread 2 is holding the file!
thread 1 is holding the file!
thread 0 is holding the file!
hello, I'm stream 0