【问题标题】:Using public static object for locking thread shared resources使用公共静态对象锁定线程共享资源
【发布时间】: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#


【解决方案1】:

如果您与其他人共享您的代码,我相信 MSDN 声明是有意义的。你永远不知道他们是否会正确使用锁,然后你的线程可能会被阻塞。 解决方案可能是将两个线程体写入同一个类。

另一方面,由于您正在处理文件,因此文件系统具有自己的锁定机制。不允许您写入正在读取的文件或读取正在写入的文件。在这种情况下,我会在同一个线程中执行读取和写入。

【讨论】:

  • 文件系统锁定取决于打开文件时请求的内容。可以安全地从正在写入的文件中读取(例如,如果写入始终是追加),因此打开文件的代码通常会要求这样做。如果代码要写入文件的各个区域,通常的做法是以独占模式打开文件,以防止在写入内容时读取文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多