【发布时间】:2015-02-03 04:13:49
【问题描述】:
让我们考虑这个例子,我有两个类:
Main_Reader -- 从文件中读取
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 -- 写入文件
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());
}
}
}
在 main 中,用两个线程实例化了两个函数。
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----------");
}
为了使这个线程安全,我使用了一个公共静态字段,
public static object tloc=new object(); //in class Main_Reader
我的问题是,这是一个好方法吗?
因为我在某个 MSDN 论坛上阅读过:
避免锁定公共类型
还有其他方法可以使这个线程安全吗?
【问题讨论】:
-
如果你只是从类本身中锁定它,为什么还要公开你锁定的对象?
-
@Servy:因为他有两个班
-
@SLaks 啊,没看出它们是不同的类。那么新的问题,为什么这些在不同的类,而不是一个类?
-
为什么不将 tlock 标记为内部?我想这两个类都在同一个程序集中,对吧?
-
所以您知道这不是一个好方法,并且大概已经searched 用于类似stackoverflow.com/questions/6112316/… 之类的问题......您能否澄清一下您在这个问题中寻求什么样的帮助?跨度>
标签: c#