I use .net 4.0 and i've tried to figure out how to use async method to await DocumentCompleted event to complete and return the value. My original code is above, how can i turn it into async/await model in this scenario ?
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);
}
When a asynchronous method is executed, the code runs but nothing happens other than a compiler warning.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete.
Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.
We start a timer, this will allow us to time the code to see how long the code will run for. The solution. In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise.
So we need a method that returns a task when the DocumentCompleted
event fires. Anytime you need that for a given event you can create a method like this:
public static Task WhenDocumentCompleted(this WebBrowser browser)
{
var tcs = new TaskCompletionSource<bool>();
browser.DocumentCompleted += (s, args) => tcs.SetResult(true);
return tcs.Task;
}
Once you have that you can use:
await browser.WhenDocumentCompleted();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With