Thread safe StreamWriter C# how to do it? 1

user349026 picture user349026 · Aug 28, 2010 · Viewed 9.5k times · Source

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);
    } 

Answer

desco picture desco · Aug 28, 2010

TextWriter.Synchronized

Creates a thread-safe wrapper around the specified TextWriter. ll writes to the returned wrapper will be thread safe.