等待使用 AutoResetEvent 处理事件 [英] Waiting for event to be handled with AutoResetEvent
本文介绍了等待使用 AutoResetEvent 处理事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想停止执行我的代码,直到网站加载完毕(我使用 Windows.Forms.WebBrowser).我读到我应该使用 AutoResetEvent,但我之前没有使用任何与线程相关的类.我写了这段代码,但它只会冻结我的程序,如何解决?
I want to stop performing my code till website will be loaded(I use Windows.Forms.WebBrowser). I read that I should use AutoResetEvent, but I don't use any class related to threading before. I write this code, but it only freeze my program, how fix it?
var evt = new AutoResetEvent(false);
webBrowser.DocumentCompleted += (sender1, e1) =>
{
if (webBrowser.ReadyState == WebBrowserReadyState.Complete)
{
evt.Set();
}
};
webBrowser.Navigate("https://www.google.com/");
evt.WaitOne(); //wait to evt.Set() call
//...
//further code
推荐答案
你可以使用 async/await 并且可以使用 TaskCompletionSource 而不是 AutoResetEvent
You can utilize async/await and can use TaskCompletionSource instead of AutoResetEvent
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
webBrowser.DocumentCompleted += (sender1, e1) => tcs.TrySetResult(null);
webBrowser.Navigate("https://www.google.com/");
await tcs.Task;
这篇关于等待使用 AutoResetEvent 处理事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文