async method with completed event

2019-02-05 04:52发布

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);
    }

1条回答
倾城 Initia
2楼-- · 2019-02-05 05:07

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();
查看更多
登录 后发表回答