confusedMind
confusedMind

Reputation: 2653

Lock not working properly in c#

I put lock on a few lines which are supposed to get cookie files and read them, but I see sometimes an error saying file already in use! So not sure whats going wrong...

Code:

private Object cookieLock = new Object();

main{
    for (int j = 0; j < maxThreads; j++)
        {
            //   Thread thread = new Thread(new ThreadStart(startPosting2(worker)));
            Thread thread = new Thread(() => postingFunction2());
            thread.IsBackground = true;
            thread.Start();
        }
    }

public void postFunction2()
{
 string tmpUsername = string.Empty;
 string[] array2 = null;
   try
    {
      lock (cookieLock)
       {
          array2 = File.ReadAllLines(tmpUsername + ".txt");
       }
    }
   catch(Exception ex)
    {
      TextWriter sUrl = new StreamWriter("readingSameCookieFile.txt", true);
      sUrl.WriteLine(exp.ToString());
      sUrl.Close();
    }
}

Am I doing anything wrong? These lines are executed by 20-100 threads simultaneously, I do not see it much but I do see it some time, so wondering why!

TXT FILE ERROR:

System.IO.IOException: The process cannot access the file 'C:\Users\Administrator\My Projects\Bot Files\2 Message Poster Bot\MessagePoster - NoLog - Copy\cookies\LaureneZimmerebner57936.txt' because it is being used by another process.

Upvotes: 1

Views: 384

Answers (3)

weston
weston

Reputation: 54791

If you just want to overcome the problem you are having and are sure it's not beeing written then you can use this function instead of File.ReadAllLines. The key is it the share options it gives FileShare.ReadWrite.

private static string[] ReadAllLines(string fileName)
{
  using (var fs = new FileStream(fileName, FileMode.Open,
                                           FileAccess.Read,
                                           FileShare.ReadWrite))
  {
    var reader = new StreamReader(fs);
    //read all at once and split, or can read line by line into a list if you prefer
    var allLines = reader.ReadToEnd().Split(new string[] { "\r\n", "\r", "\n" },
                                            StringSplitOptions.None);
    return allLines;
  }
}

Upvotes: 0

Vignesh.N
Vignesh.N

Reputation: 2666

You are trying to read cookies; may be the browser or some other application outside your code is accessing/writing to the cookie file, hence the exception.

you have not posted the entire code, just make sure the lock object is not instantiated multiple times or make it static to be sure. Also try adding Thread.Sleep(0) after reading; see if that helps.

If you writing the contents of array2 to another file, make sure that is disposed/closed properly after writing.

tryin putting the entire method inside the lock block

public void postFunction2() 
{ 
 lock (cookieLock) 
 { 
 string tmpUsername = string.Empty; 
 string[] array2 = null; 
   try 
    { 
          array2 = File.ReadAllLines(tmpUsername + ".txt"); 
    } 
   catch(Exception ex) 
    { 
      TextWriter sUrl = new StreamWriter("readingSameCookieFile.txt", true); 
      sUrl.WriteLine(exp.ToString()); 
      sUrl.Close(); 
    } 
  }
} 

Upvotes: 1

Mahmoud Fayez
Mahmoud Fayez

Reputation: 3459

I would suggest to read file only once and share array2 among the 20-100 thread, because reading it multiple times will cause performance degradations. Also in multithreading environment it is recommended to keep all I/O operations in single thread.

Sharing array2 won't require locks if it will be only read by all threads.

Debug.Write(file name);// to make sure each thread opens different file.

Upvotes: 1

Related Questions