从事件C#锁定 [英] C# Locking from events

查看:293
本文介绍了从事件C#锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#构造,就像是锁{},但工程从事件处理程序,即等待代码块处理后续事件之前完成时调用。



我遇到的问题是,锁{}只防止其它线程从获得对象上的锁,但如果在同一线程上的事件处理程序被调用时,的锁定块内码的执行被中断,并且新的事件被返回到原代码执行之前办理

 对象DoStuffLock =新的对象(); 

公共无效DoStuff()
{
锁(DoStuffLock)
{
//难道我们不希望被打扰的东西,
//而是因为它是从一个事件处理
称为//它仍然可以尽管锁定
}
}
<中断/ pre>

目前我周围像这样的问题,工作(但它几乎没有理想的):

 对象DoStuffLock =新的对象(); 

//这会从一个事件调用,因此可以被打断,
//锁定没有帮助,所以推出单独的线程
公共无效DoStuff()
{
变种x =新的Thread(DoStuffInternal);
x.Start();
}

私人无效DoStuffInternal()
{
锁(DoStuffLock)
{
//做的东西,我们不希望被打断
}
}


解决方案
< BLOCKQUOTE>

我遇到的问题是,锁{}只是阻止其他线程获取对象上的锁,但如果在同一线程上的事件处理程序被称为




这真的是不可能发生的。如果你的线程执行,不能发生一个事件的在同一个线程的 - 它必须要在不同的线程上调



话虽这么说,你的第二个办法,在许多方面,在任何情况下更胜一筹。这里有一个隐含的假设,事件处理程序将返回得非常快。 A堵事件处理通常是一个糟糕的设计的标志,并且有可能导致问题,尤其是因为事件发布者将不被期待阻断事件。


Is there a construct in c# that is like lock { }, but works when called from an event handler i.e. waits for the code block to complete before handling a subsequent event.

The problem I am having is that lock { } only prevents other threads from obtaining a lock on the object, but if an event handler on the same thread is called, the execution of code within the lock block is interrupted, and the new event is handled before returning to the execution of the original code.

object DoStuffLock = new object();

public void DoStuff()
{
    lock (DoStuffLock)
    {
         // Do stuff that we don't want to be interrupted,
         // but because it is called from an event handler 
         // it still can be interrupted despite the lock
    }
}

I am currently working around the problem like this (but it is hardly ideal):

object DoStuffLock = new object();

// this gets called from an event, and therefore can be interrupted, 
// locking does not help, so launch separate thread
public void DoStuff()
{
    var x = new Thread(DoStuffInternal);
    x.Start();
}

private void DoStuffInternal()
{
    lock (DoStuffLock)
    {
         // Do stuff that we don't want to be interrupted
    }
}

解决方案

The problem I am having is that lock { } only prevents other threads from obtaining a lock on the object, but if an event handler on the same thread is called

This really can't happen. If your thread is executing, an event can't occur on the same thread - it would have to be raised on a different thread.

That being said, your "second approach" is, in many ways, superior in any case. There's an implicit assumption that event handlers will return very quickly. A "blocking" event handler is typically a sign of a bad design, and will potentially cause problems, especially since the event publisher will not be expecting the event to block.

这篇关于从事件C#锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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