异步方法完成事件事件、方法

2023-09-03 02:07:51 作者:孤烟°

我用.NET 4.0和我一直试图弄清楚如何使用异步方法来等待DocumentCompleted事件的完成和返回值。我原来的code是上面的,我怎么可以把它变成异步/待机模式在这种情况?

 私有类BrowserWindow
    {
        私人布尔webBrowserReady = FALSE;
        公共字符串的内容=;


        公共无效导航(字符串URL)
        {

            XXX浏览器=新XXX();

            browser.DocumentCompleted + =新的EventHandler(wb_DocumentCompleted);
            webBrowserReady = FALSE;
            browser.CreateControl();
            如果(browser.IsHandleCreated)
                browser.Navigate(URL);


            而(!webBrowserReady)
            {
                //Application.DoEvents(); >>它与异步替换/等待
            }

        }

        私人无效wb_DocumentCompleted(对象发件人,EventArgs的)
        {
            尝试
            {
               ...

                  webBrowserReady = TRUE;

                  内容= browser.Document.Body.InnerHtml;

            }
            抓住
            {

            }

        }

        公共委托串AsyncMethodCaller(字符串URL);
    }
 

解决方案

因此​​,我们需要返回一个任务 DocumentCompleted 事件触发时的方法。任何时候你需要的,对于一个给定的事件,你可以创建这样一个方法:

 公共静态任务WhenDocumentCompleted(此web浏览器浏览器)
{
    VAR TCS =新TaskCompletionSource<布尔>();
    browser.DocumentCompleted + =(S,参数)=> tcs.SetResult(真正的);
    返回tcs.Task;
}
 

一旦你有,你可以使用:

 伺机browser.WhenDocumentCompleted();
 
揭秘一线互联网企业 前端JavaScript高级面试 笔记

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

解决方案

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