我使用 .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);
}
最佳答案
所以我们需要一个方法,在 DocumentCompleted
事件触发时返回一个任务。任何时候你需要为给定的事件创建一个这样的方法:
public static Task WhenDocumentCompleted(this WebBrowser browser)
{
var tcs = new TaskCompletionSource<bool>();
browser.DocumentCompleted += (s, args) => tcs.SetResult(true);
return tcs.Task;
}
一旦有了,您就可以使用:
await browser.WhenDocumentCompleted();
关于c# - 具有完成事件的异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836416/