編輯:運行一些測試(單聲道),我不是很確定這是最好的方法。
我沒有設法使任何事情崩潰,但執行只是在Run()
之後暫停幾秒鐘,然後再回到調用方。所以我懷疑這不是代碼片斷的好兆頭。
這就是說,測試的情況是不切實際的。
另一種選擇是在FileShare.ReadWrite
模式打開的文件,並讓OS關心lockings。
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
還是應該將其存儲在數據庫中。這將解決併發問題,並在出現問題時保持原子化。 –
我建議你使用數據庫,並根據你的需要實現'樂觀'或'悲觀'併發。 – RAS
你爲什麼會認爲會'崩潰'?請詳細說明。不要解決你沒有的問題。 – avishayp