Asynchronous method with a completed event

I am using .net 4.0 and I tried to figure out how to use the async method to wait for the DocumentCompleted event to complete and return a value. My source code is above, how can I turn it into an asynchronous / waiting 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); } 
+6
source share
1 answer

So, we need a method that returns a task when the DocumentCompleted event fires. At any time, when it is necessary for this event, you can create such a method:

 public static Task WhenDocumentCompleted(this WebBrowser browser) { var tcs = new TaskCompletionSource<bool>(); browser.DocumentCompleted += (s, args) => tcs.SetResult(true); return tcs.Task; } 

After that you can use:

 await browser.WhenDocumentCompleted(); 
+9
source

All Articles