What is the best way to build a program that is thread safe in terms that it needs to write double values to a file. If the function that saves the values via streamwriter is being called by multiple threads? Whats the best way of doing it?
Code from comment:
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);
}
Edit, after decoding the code in your comment
Your problem is not with locking or threads but with capturing the loop variable. This is a classic problem, all your threads run with a ‘capture’ of the single
Vvariable, and by the time the threads are executed it will have reached its final value of 999. Except maybe for the first few Workitems.So, instead of :
use
or, a little more concise,
As a variation on @Matti’s answer, it is recommended to lock on a separate simple object. This reduces the risk of anything else locking on the same object (the StreamWriter code itself for instance).
But the way you have set up the
SaveValues(StreamWriter writer, ...)method make it a little more complicated. It is better to have an object wherewriterandwriterLockare both private members.