就需要将双精度值写入文件而言,构建线程安全程序的最佳方法是什么。如果通过streamwriter保存值的函数被多个线程调用?最好的方法是什么?
评论中的代码:
static void Main()
{
List<double> Values = new List<double>();
StreamWriter writer = new StreamWriter("test.out");
for (int i = 0; i < 1000; i++) Values.Add(i);
foreach (double V in Values)
{
ThreadPool.QueueUserWorkItem(delegate(object state) { SaveValues(writer, V); }, V);
}
}
static void SaveValues(StreamWriter writer, double Value)
{
lock (writer) writer.WriteLine(Value);
}