0

Lets Consider the example, I have two classes:

Main_Reader -- Read from file

public  class Main_Reader
{
   public static object tloc=new object();
   public void Readfile(object mydocpath1)
   {
       lock (tloc)
       {
           string mydocpath = (string)mydocpath1;
           StringBuilder sb = new StringBuilder();
           using (StreamReader sr = new StreamReader(mydocpath))
           {
               String line;
               // Read and display lines from the file until the end of 
               // the file is reached.
               while ((line = sr.ReadLine()) != null)
               {
                   sb.AppendLine(line);
               }
           }
           string allines = sb.ToString();
       }
   }
}

MainWriter -- Write the file

public  class MainWriter
{
  public void Writefile(object mydocpath1)
  {
      lock (Main_Reader.tloc)
      {
          string mydocpath = (string)mydocpath1;
          // Compose a string that consists of three lines.
          string lines = "First line.\r\nSecond line.\r\nThird line.";

          // Write the string to a file.
          System.IO.StreamWriter file = new System.IO.StreamWriter(mydocpath);
          file.WriteLine(lines);
          file.Close();
          Thread.Sleep(10000);
          MessageBox.Show("Done----- " + Thread.CurrentThread.ManagedThreadId.ToString());
      }
  }
}

In main have instatiated two function with two threads.

 public string mydocpath = "E:\\testlist.txt";  //Here mydocpath is shared resorces
     MainWriter mwr=new MainWriter();

     Writefile wrt=new Writefile();

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t2 = new Thread(new ParameterizedThreadStart(wrt.Writefile));
        t2.Start(mydocpath);
        Thread t1 = new Thread(new ParameterizedThreadStart(mrw.Readfile));
        t1.Start(mydocpath);
        MessageBox.Show("Read kick off----------");

    }

For making this thread safe, i am using a public static field,

public static object tloc=new object();   //in class Main_Reader

My Question is, is this a good approach?

Because I read in one of MSDN forums:

avoid locking on a public type

Is there another approach for making this thread safe?

eebbesen
  • 5,070
  • 8
  • 48
  • 70
user2866116
  • 171
  • 1
  • 1
  • 6
  • 1
    Why have you made the object you're locking on public if you only ever lock on it from withing the class itself? – Servy Feb 02 '15 at 19:55
  • 1
    @Servy: Because he has two classes – SLaks Feb 02 '15 at 19:57
  • 2
    @SLaks Ah, didn't see that they were different classes. So then new question, why are these in different classes, and not a single class? – Servy Feb 02 '15 at 19:58
  • 1
    Why not mark the tlock internal? I suppose both classes will be in the same assembly, right? – Mihai Caracostea Feb 02 '15 at 20:01
  • So you know it is not a good approach and presumably already [searched](http://www.bing.com/search?q=c%23+why+not+lock+public) for similar questions like http://stackoverflow.com/questions/6112316/why-locking-on-a-public-object-is-a-bad-idea... Could you please clarify what kind of help you are looking in this question? – Alexei Levenkov Feb 02 '15 at 20:01
  • What are you trying to achieve? Randomly either first read or first write the same file? Also, is there any specific reason for having the `Thread.Sleep()` and `MessageBox.Show()` calls under a `lock`? – Ondrej Tucny Feb 02 '15 at 20:02

1 Answers1

0

I believe the MSDN statement has meaning if you share your code with other people. You never know if they are going to use the locks properly, and then your threads might get blocked. The solution is probably to write both thread bodies into the same class.

On the other hand, since you're dealing with files, the filesystem has a locking mechanism of its own. You won't be allowed to write into a file that is being read, or read of file that is being written. In a case like this, I would perform the reading and the writing in the same thread.

  • File system locking depends on what was requested when the file was opened. It is possible to read from a file that is being written to safely (for instance, if the write is always an append), so this is often requested by code opening a file. If code is going to write in various areas of a file, the common practice is to open the file in an exclusive mode, to prevent reading from the file while its contents are being written. – StarPilot Feb 02 '15 at 20:36