-1

简要说明是我试图用我无法控制的第三方 DLL 启动几个连接事件。一旦发生连接,就会触发一个事件。

我需要在主线程上等待直到发生这种情况,但是每次设置它都会锁定主线程。

private EventWaitHandle _waitForChannel = new AutoResetEvent(false);

调用代码

new Thread(StartInstrumentMonitoring).Start();

=--------

public void StartInstrumentMonitoring(){
if(this.instrumentList.Count == 0){
    new Thread(startConnections).Start()
_waitForChannel.WaitOne();

=-----------------------------

public void startCOnnections(){
 CODE HERE TO DETERMINE INSTRUMENT
 instrument.connectionReceived += instrument_connectionEvent;

instrument_connectionEvent(object sender, ResultEventArgs e){

            if (sender.Name == instrument.Identifier || sender.Identifier == instrument.Identifier)
                _waitForChannel.Set();
}

这段代码的问题在于,在执行 StartInstrumentMonitoring 后,它会在对第三方 DLL 进行必要的调用并附加事件处理程序以与所述库进行交互之后返回。这显然调用 WaitOne() 阻止我正在阻止我捕获从返回的事件的主线程instrument_ConnectionEvent

4

1 回答 1

0

如果instrument_ConnectionEvent根本没有调用 3rd 方库肯定有可能试图在主线程上触发事件,这将导致您当前代码的死锁。

AutoResetEvent您可以使用简单的条件检查来查看您的连接是否已建立,而不是使用。您可以调用Application.DoEvents()循环来强制处理消息队列。

while(<check condition> == false)
{
    Application.DoEvents();
}
于 2015-10-07T16:39:32.600 回答