How to have synchronous writing to a file (Threads) ?

Posted by bobby on Stack Overflow See other posts from Stack Overflow or by bobby
Published on 2010-03-12T09:33:44Z Indexed on 2010/03/12 9:37 UTC
Read the original article Hit count: 171

Filed under:

Hi all. I created and started some Threads that each one writes something to a common text file. but the following error appears to me: "The process cannot access the file 'C:\hello.txt' because it is being used by another process."

void AccessFile()

    {

        int num = 5;

        Thread[] trds = new Thread[5];

        for (int i = 0; i < num; i++)

        {

            trds[i] = new Thread(new ParameterizedThreadStart(WriteToFile));

        }

        for (int i = 0; i < num; i++)

        {

            trds[i].Start(String.Format("{0}: Hello from thread id:#{1}", i, trds[i].ManagedThreadId));

        }

    }





    void WriteToFile(object message)

    {

        string FileName = "C:\\hello.txt";

        string mess = (string)message;

        System.IO.StreamWriter sw = null;

        FileStream objStream = null;

        sw = File.AppendText(FileName);

        if (sw == null)

        {

            objStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

            sw = new StreamWriter(objStream);

        }

        sw.WriteLine(mess);

        sw.Close();

        sw.Dispose();

    }

the AccessFile() method is the starting point. could any one tell me what should i do?

© Stack Overflow or respective owner

Related posts about multithreading