6
异步方法我使用.NET 4.0和我一直试图弄清楚如何使用异步方法来等待DocumentCompleted事件完成并返回值。我的原始代码在上面,我怎么能把它变成这种情况下的异步/等待模型?与完成的事件
private class BrowserWindow
{
private bool webBrowserReady = false;
public string content = "";
public void Navigate(string url)
{
xxx browser = new xxx();
browser.DocumentCompleted += new EventHandler(wb_DocumentCompleted);
webBrowserReady = false;
browser.CreateControl();
if (browser.IsHandleCreated)
browser.Navigate(url);
while (!webBrowserReady)
{
//Application.DoEvents(); >> replace it with async/await
}
}
private void wb_DocumentCompleted(object sender, EventArgs e)
{
try
{
...
webBrowserReady = true;
content = browser.Document.Body.InnerHtml;
}
catch
{
}
}
public delegate string AsyncMethodCaller(string url);
}
感谢您的很好的解决方案,但一个问题是,我” m使用vs 2010和.net 4.0,所以我必须使用旧式而不是等待synctax(4.5)。我有点困惑如何让它在4.0 – 2013-02-12 16:42:03
@namvo工作你明确地说,你想要一个使用async/await的解决方案,所以我认为你使用的是兼容包。如果你不是,那么只需在方法返回的任务上使用'ContinueWith'('WhenDocumentCompleted'事件将在4.0中工作),并将文档完成后运行的代码放在那里。为了方便起见,您最可能要使用lambda表达式。 – Servy 2013-02-12 16:46:28
谢谢,我会玩它。 – 2013-02-12 16:54:00