如何阻止直到事件在C#中触发 [英] How to block until an event is fired in c#
问题描述
问了这个问题后,我想知道是否可以等待事件被触发,然后获取事件数据并返回其中的一部分.像这样:
After asking this question, I am wondering if it is possible to wait for an event to be fired, and then get the event data and return part of it. Sort of like this:
private event MyEventHandler event;
public string ReadLine(){ return event.waitForValue().Message; }
...
event("My String");
...elsewhere...
var resp = ReadLine();
请确保您提供的任何解决方案都直接返回值,而不是从其他方式获取值.我在问上面的方法是否可以某种方式使用.我知道Auto/ManuelResetEvent,但我不知道它们像上面一样直接返回值.
Please make sure whatever solution you provide returns the value directly rather than getting it from something else. I'm asking if the method above is available in some way. I know about Auto/ManuelResetEvent, but I don't know that they return the value directly like I did above.
更新:我使用MyEventHandler
(其中包含Message
字段)声明了一个事件.我在另一个名为ReadLine
的线程中有一个方法,等待事件触发.当事件触发WaitForValue方法(事件处理场景的一部分)时,将返回事件args,其中包含消息.然后,该消息由ReadLine返回给调用它的对象.
Update: I declared an event using MyEventHandler
(which contains a Message
field). I have a method in another thread called ReadLine
waiting for the event to fire. When the event fires the WaitForValue method (part of the event handling scene) returns the event args, which contains the message. The message is then returned by ReadLine to whatever had called it.
The accepted answer to that question I asked was what I did, but it just doesn't feel quite right. It almost feels like something could happen to the data between the ManuelResetEvent firing and the program retrieving the data and returning it.
更新:Auto/ManualResetEvent
的主要问题是它太容易受到攻击.线程可以等待事件,然后在将其更改为其他内容之前,没有给其他人足够的时间来获取它.有没有办法使用锁或其他东西?也许使用get和set语句.
Update: The main problem with the Auto/ManualResetEvent
is that it is too vulnerable. A thread could wait for the event, and then not give enough time for anyone else to get it before changing it to something else. Is there a way to use locks or something else? Maybe using get and set statements.
推荐答案
您可以使用 ManualResetEvent .在触发辅助线程之前重置事件,然后使用 WaitOne ()方法来阻止当前线程.然后,您可以让辅助线程设置ManualResetEvent,这将导致主线程继续.像这样:
You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:
ManualResetEvent oSignalEvent = new ManualResetEvent(false);
void SecondThread(){
//DoStuff
oSignalEvent.Set();
}
void Main(){
//DoStuff
//Call second thread
System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
oSecondThread.Start();
oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
oSignalEvent.Reset();
//Do more stuff
}
这篇关于如何阻止直到事件在C#中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!