-1

I am trying to use 1 lock object and trying to write to the same file using StreamWriter in two different places under the lock but I am getting the error:

The process cannot access the file 'filename' because it is being used by another process.

Lock object defined, I used a static object:

protected static Object Semaphore = new Object();

if(x != null)
{
    lock (Semaphore)
    {
        using (StreamWriter sw = new StreamWriter(fileName))
        {

            sw.WriteLine(a + "," + b + "," + c);
            sw.Close();
            sw.Flush();
        }
    }

}

Right after this:

if(y != null)
{
    lock (Semaphore)
    {
        using (StreamWriter sw1 = new StreamWriter(fileName))
        {

            sw1.WriteLine(a + "," + b + "," + c);
            sw1.Close();
            sw1.Flush();
        }
    }
}

What am I missing? Thank you.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
Sid
  • 1,145
  • 5
  • 17
  • 24
  • You need to show how you are using this code because that is the important part. – CodingYoshi Nov 05 '17 at 08:19
  • No need for close and flush in this code. using will dispose the streamwriter and that will flush and close it too – Sir Rufo Nov 05 '17 at 08:44
  • 1
    You really need to provide a [mcve] for us to see this issue in action. Right now your code looks great so there is nothing that we can answer. – Enigmativity Nov 05 '17 at 09:13

1 Answers1

0

The file is still marked as "in use" by your operating system - the error message is not from your semaphore mechanism. Normally I would think that the semaphore in combination with using should close the file for good.

Which of the 2 code parts throws your exception? Do you open it anywhere else?

Btw. please copy&paste / Fix your code - your pasted demo code will not run - closed Textwriters can not be flushed!

MY testcase - not yet threaded:

internal class Program
{
    public static void DoStuff()
    {
        Directory.CreateDirectory(Path.GetDirectoryName(fileName));

        if (x != null)
        {
            lock (lockObj)
            {
                WriteStuff();
            }
        }

        if (y != null)
        {
            lock (lockObj)
            {
                WriteStuff();
            }
        }
    }


    private static string fileName = "C:\\temp\\tempfile.txt";
    private static object lockObj = new object();
    private static string x = "";
    private static string y = "";

    static void Main(string[] args)
    {
        DoStuff();
    }

    static void WriteStuff()
    {
        using (StreamWriter sw1 = new StreamWriter(fileName))
        {
            sw1.WriteLine("irrelevant");
        }
    }
}
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69