等待事件被处理
我有一个函数,我们将其称为 Func1,它包含
Func2 &事件处理程序。
现在我想要实现的是不让
函数(Func1)返回值,直到Func2触发并处理事件。
基本上 Func1 将字符串作为返回值,并且字符串值在事件处理程序内设置。所以我需要等待事件被处理然后返回值。
代码示例
public static string Fun1 ()
{
string stringToReturn = String.Empty;
Func2(); //Func2 will after few sec fire event bellow
example.MyEvent += (object sender, WebBrowserDocumentCompletedEventArgs e) =>
{
stringToReturn = "example"; //this wont be hardcoded
};
//wait for event to be handled and then return value
return stringToReturn;
}
I have a function, let's call it Func1 and it contains
Func2 & event handler.
Now what I would like to achieve is not let
function (Func1) return value till Func2 fires and handles event.
Basically Func1 has string as return value and string value is set inside event handler. So I need to wait for event to be handled and then return value.
Code Example
public static string Fun1 ()
{
string stringToReturn = String.Empty;
Func2(); //Func2 will after few sec fire event bellow
example.MyEvent += (object sender, WebBrowserDocumentCompletedEventArgs e) =>
{
stringToReturn = "example"; //this wont be hardcoded
};
//wait for event to be handled and then return value
return stringToReturn;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
AutoResetEvent
类。使用var evt = new AutoResetEvent(false);
实例化它,在要等待的地方调用evt.WaitOne()
,然后evt.Set();< /code> 您想要在其中发出等待代码可以继续进行的信号。
如果您遇到许多涉及事件的“等到”情况,您还可以查看 反应式扩展 (接收)。
You could use the
AutoResetEvent
class. Instantiate it withvar evt = new AutoResetEvent(false);
, callevt.WaitOne()
where you want to wait, andevt.Set();
where you want to signal that the waiting code may proceed.If you have many "wait until" situations that involve events, you could also look into Reactive Extensions (Rx).
一个简单的信号量还不够吗?
Wouldn't a simple semaphore suffice?
由于
Func2
与Func1
在同一线程上运行,因此Func1
不会在Func2
返回之前返回。这意味着可以保证在Func2
中触发的事件在将控制权返回给Func1
之前被触发。只需在调用Func2
之前附加事件处理程序,它就会按预期工作。在这种情况下,使用
Semaphore
或AutoResetEvent
就显得有些过分了,因为两者都需要获取操作系统资源来管理线程同步。As
Func2
runs on the same thread asFunc1
,Func1
will not return beforeFunc2
returns. This means it is guaranteed that the event fired inFunc2
is getting fired before it returns control toFunc1
. Just attach your event handler before callingFunc2
and it should work as expected.Using a
Semaphore
or anAutoResetEvent
is overkill in this scenario as both acquire OS resources to manage thread synchronization.