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?