只有一个锁定的对象“死机”? [英] 'Deadlock' with only one locked object?

查看:140
本文介绍了只有一个锁定的对象“死机”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个线程在C#中的一个问题。 我用事件从另一个线程,为此,我需要使用过程中的调用()命令更新窗体标签。 这部分也工作正常。 然而,用户可以关闭形式,此处的程序可以崩溃如果事件被发送在一个不幸的时间

I am having a problem with multi threading in C#. I use an event to update a label in a form from another thread, for which I need to use the Invoke() command of course. That part is also working fine. However, the user can close the form and here the program can crash if the event is sent at an unfortunate time.

所以,我以为我会简单地覆盖形式的Dispose()方法,设置一个布尔为true内锁定code,还检查布尔和调用的锁定code中的事件。

So, I thought I would simply override the Dispose() method of the form, set a boolean to true within locked code, and also check that boolean and invoke the event in locked code.

不过,我每次关闭程序完全冻结的形式。

However, every time I close the form the program freezes completely.

下面是在code所提到的部分:

Here are the mentioned parts of the code:

private object dispose_lock = new object();
private bool _disposed = false;

private void update(object sender, EventArgs e)
{
    if (InvokeRequired)
    {
        EventHandler handler = new EventHandler(update);
        lock (dispose_lock)
        {
            if (_disposed) return;
            Invoke(handler); // this is where it crashes without using the lock
        }
        return;
    }

    label.Text = "blah";
}

protected override void Dispose(bool disposing)
{
    eventfullObject.OnUpdate -= update;
    lock (dispose_lock) // this is where it seems to freeze
    {
       _disposed = true; // this is never called
    }
    base.Dispose(disposing);
}

我希望有人在这里有任何想法有什么不对的code。 预先感谢您!

I hope anyone here has any idea what is wrong with this code. Thank you in advance!

推荐答案

我真的会何去何从简单。相反,实施棘手的线程安全的code,我只想捕捉到了异常,什么也不做,如果它失败。

I really would go simple here. Instead of implementing tricky thread-safe code, I would simply catch the exception and do nothing if it fails.

假设它是一个的ObjectDisposedException

try
{
    this.Invoke(Invoke(handler));
}
catch (ObjectDisposedException)
{
    // Won't do anything here as
    // the object is not in the good state (diposed when closed)
    // so we can't invoke.
}

这是简单,pretty的简单。如果注释指定的为什么的你捕获该异常,我认为这是确定。

It's simpler and pretty straightforward. If a comment specifies why you catch the exception, I think it's OK.

这篇关于只有一个锁定的对象“死机”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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