Longtime reader, first-time poster here.
My goal: To be able to take advantage of async/await while using the WebBrowser class. As the WebBrowser.Navigate(string url) is an asynchronous method, and you can't examine the html document until the LoadComplete event is fired.
Here is my (working) code so far:
public class AsyncWebBrowser
{
protected WebBrowser m_WebBrowser;
private ManualResetEvent m_MRE = new ManualResetEvent(false);
public void SetBrowser(WebBrowser browser) {
this.m_WebBrowser = browser;
browser.LoadCompleted += new LoadCompletedEventHandler(WebBrowser_LoadCompleted);
}
public Task NavigateAsync(string url) {
Navigate(url);
return Task.Factory.StartNew((Action)(() => {
m_MRE.WaitOne();
m_MRE.Reset();
}));
}
public void Navigate(string url) {
m_WebBrowser.Navigate(new Uri(url));
}
void WebBrowser_LoadCompleted(object sender, NavigationEventArgs e) {
m_MRE.Set();
}
}
And this previous class now allows me to use the following:
public async void NavigateToGoogle() {
await browser.NavigateAsync("www.google.com");
//Do any necessary actions on google.com
}
However, I am wondering if there is a more efficient/proper way of handling this. Specifically, the Task.Factory.CreateNew with the blocking ManualResetEvent. Thanks for your input!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…