How to have synchronous writing to a file (Threads) ?
- by bobby
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?