C#我是否正确使用锁? [英] C# Am i using lock correctly?

查看:84
本文介绍了C#我是否正确使用锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试编写线程安全的记录器类.我对这方面的正确设计和最佳实践不是很熟悉.我的代码有缺陷吗?

I'm currently trying to write a thread-safe logger class. I'm not very familiar with correct design and best practices in this area. Is there a flaw in my code?

public class WriteStuff
{
    private readonly StreamWriter m_Writer;
    private readonly object m_WriteLock = new object ();

    public WriteStuff(String path)
    {
        m_Writer = File.CreateText (path);

        m_Writer.WriteLine ("x");
        m_Writer.Flush ();
    }

    public void ListenTo(Foo foo)
    {
        foo.SomeEvent += new EventHandler<SomeArgs> (Foo_Update);
    }

    private void Foo_Update(object sender, SomeArgs args)
    {
        lock (m_WriteLock) {
            m_Writer.WriteLine (args);
            m_Writer.Flush ();
        }
    }
}

推荐答案

从多线程角度看,您发布的内容看起来不错.尽管我可能是错的,但看起来进行任何多线程处理(甚至使用foo对象)的任何其他代码也应该是安全的.当然,在该部分代码中我看不到任何死锁

What you've posted looks fine from a multi-threading perpective. Although I could be wrong, it would appear that any other code that does some multi-threading (even using the foo object) should be safe. Certainly, I can't see any deadlocks in the that section of code.

无论如何,有几件事值得注意(除了对死锁非常谨慎并进行严格测试以确保它们不会发生之外):

A few things worth noting anyway (apart from being very careful with deadlocks and testing rigourously to insure they won't occur):

  • 最好在构造函数中放置代码锁定,因为我认为在某些情况下可以在构造函数块执行完毕之前调用方法的是可能. (如果我错了,请纠正我.)
  • 在这种情况下,StreamWriter对象是私有的,这很好.如果它是受保护的或内部的,那么您肯定必须对其他代码如何利用该对象保持谨慎(事实上,我认为最好总是将此类对象声明为私有的).
  • 您已经锁定了正确的方法!锁定一个单独的私有实例对象始终是最安全的,因为您知道该对象不能被您自己的代码以外的任何其他代码锁定(如果您锁定thisStreamWriter对象本身).
  • It's best to put a lock around the code within the constructor, as I believe it's possible in certain circumstances that methods can be called before the constructor block has finished executing. (Someone please correct me if I'm wrong on this one.)
  • The StreamWriter object in this case is private, which is good. If it were protected or internal you would certainly have to be cautious about how other code utilised the object (in fact I think it would be best to almost always declare such objects as private).
  • You've done locking the right way! It's always safest to lock on a separate private instance object because you know that object can't be locked by any other code than your own (which isn't the case if you lock this or the StreamWriter object itself).

仍然,我可能会丢失一些东西,上面未显示的其他一些代码也可能会引起问题,但是据我所知,除了 possible <之外,该代码没有缺陷. /em>缺少关于构造函数代码的锁定.当您开始执行更复杂的多线程时,尤其是在类/实例之间时,您更有可能需要注意死锁情况.

Still, I may be missing something, and there is a small possibility that some other code not shown above might cause problems, but as far as I can see it that code isn't flawed except for a possible missing lock around the constructor code. You're more likely to have to watch out for deadlock situations when you start doing more complex multi-threading, especially across classes/instances.

无论如何,希望能有所帮助.

Anyway, hope that helps.

这篇关于C#我是否正确使用锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆