目录
原以为设置了文件共享模式为允许随后写入(FileShare.Write),就可以实现多线程下的正常写入操作,实际情况是使用该模式后不会报线程独占问题,但是写入的内容是不完整的,比如开了n个线程,真正写入的内容不仅时序上不连续,且内容也不完整;还是需要额外加锁后才能保证时序及内容的完整性。
using System.Text;
public class Program
{
static int SuccessCount = 0;
static int FailureCount = 0;
static ReaderWriterLockSlim WriteLock = new ReaderWriterLockSlim();
static object Lock = new object();
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
var result = Parallel.For(0, 30, action =>
{
WriteTest();
});
Console.WriteLine("写入中...");
Console.ReadLine();
}
static void WriteTest()
{
try
{
WriteLock.EnterWriteLock();
//lock (Lock)
//{
using (FileStream logFile = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
{
SuccessCount++;
Console.WriteLine("count:" + SuccessCount);
var count = SuccessCount;
var logContentBytes = Encoding.Default.GetBytes($"{Thread.CurrentThread.ManagedThreadId}, {DateTime.Now.ToString("yyyy-MM-dd:HH:mm:ss:ffff")},{count},{Environment.NewLine}");
logFile.Seek(0, SeekOrigin.End);
logFile.Write(logContentBytes, 0, logContentBytes.Length);
}
//}
}
catch (Exception ex)
{
FailureCount++;
Console.WriteLine($"Failure Count:{FailureCount}");
}
finally { WriteLock.ExitWriteLock(); }
}
}
?
如果实际应用的话,还是先塞到线程安全的队列中,再用独立线程来写入,来保证效率和一致性。