简体   繁体   中英

Asynchronus thread is not working with Async / Await

I have a WebBrowser control code in Windows Forms project. This working fine as listed below. It first navigates to my html page and then click anchor tags there. Each anchor tag will navigate to a website.

Now, I tried to make it asynchrony by adding async/await. But this is not working. Any idea what is the missing point here?

Note: I cannot change e1.InvokeMember("Click"); to webBrowser1.Navigate(). Because in my real scenario there will be javascript code that handles the navigation. Hence I need to call the InvokeMember() itself.

Reference

Async Await

C# Code

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        webBrowser1.ScriptErrorsSuppressed = true;

        webBrowser1.DocumentCompleted += ExerciseApp;
        HomoePageNavigate();

        //ProcessUrlsAsync(@"C:\Samples_L\MyTableTest.html").Start();
    }


    private Task ProcessUrlsAsync(string url)
    {
        return new Task(() =>
        {

            TaskAwaiter<string> awaiter = ProcessUrlAsyncOperation(url);
            string result = awaiter.GetResult();

            MessageBox.Show(result);

        });

    }

    // Awaiter inside
    private TaskAwaiter<string> ProcessUrlAsyncOperation(string url)
    {
        TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>();
        var handler = new WebBrowserDocumentCompletedEventHandler((s, e) =>
        {
            // TODO: put custom processing of document right here
            ExerciseApp(webBrowser1 , null);
            taskCompletionSource.SetResult(e.Url + ": " + webBrowser1.Document.Title);
        });
        webBrowser1.DocumentCompleted += handler;
        taskCompletionSource.Task.ContinueWith(s => { webBrowser1.DocumentCompleted -= handler; });

        webBrowser1.Navigate(url);
        return taskCompletionSource.Task.GetAwaiter();
    }


    private void HomoePageNavigate()
    {
        webBrowser1.Navigate(@"C:\Samples_L\MyTableTest.html");
    }

    List<string> visitedProducts = new List<string>();

    private void ExerciseApp(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

        WriteLogFunction("A");
        var wb = sender as WebBrowser;

        int catalogElementIterationCounter = 0;

        var elementsToConsider = wb.Document.All;
        string productUrl = String.Empty;

        bool isClicked = false;

        foreach (HtmlElement e1 in elementsToConsider)
        {
            catalogElementIterationCounter++;

            string x = e1.TagName;
            String idStr = e1.GetAttribute("id");

            if (!String.IsNullOrWhiteSpace(idStr))
            {
                //Each Product Navigation
                if (idStr.Contains("catalogEntry_img"))
                {
                    productUrl = e1.GetAttribute("href");
                    if (!visitedProducts.Contains(productUrl))
                    {
                        WriteLogFunction("B");
                        visitedProducts.Add(productUrl);
                        isClicked = true;
                        e1.InvokeMember("Click");
                        break;
                    }

                }
            }
        }

        if (visitedProducts.Count == 4)
        {
            visitedProducts = new List<string>();
        }

        if (!isClicked)
        {
            WriteLogFunction("C");
            HomoePageNavigate();
            //break;
        }




    }

    private void WriteLogFunction(string strMessage)
    {
        using (StreamWriter w = File.AppendText("log.txt"))
        {
            w.WriteLine("\r\n{0} ..... {1} ", DateTime.Now.ToLongTimeString(), strMessage);
        }
    }


}

HTML

<html>
<head>

    <style type="text/css">
        table {
            border: 2px solid blue;
        }

        td {
            border: 1px solid teal;
        }
    </style>

</head>
<body>

    <table id="four-grid">
         <tr>
            <td>
                <a href="https://www.wikipedia.org/" id="catalogEntry_img63666">

                    <img src="ssss"
                        alt="B" width="70" />
                </a>
            </td>
            <td>
                <a href="http://www.keralatourism.org/" id="catalogEntry_img63667">

                    <img src="ssss"
                        alt="A" width="70" />
                </a>
            </td>
        </tr>
        <tr>
            <td>
                <a href="http://stackoverflow.com/users/696627/lijo" id="catalogEntry_img63664">

                    <img src="ssss"
                        alt="G" width="70" />
                </a>
            </td>
            <td>
                <a href="http://msdn.microsoft.com/en-US/#fbid=zgGLygxrE84" id="catalogEntry_img63665">

                    <img src="ssss"
                        alt="Y" width="70" />
                </a>
            </td>
        </tr>

    </table>
</body>

</html>

Now, I tried to make it asynchrony by adding async/await. But this is not working. Any idea what is the missing point here?

Despite the question's title, you don't use async or await keywords anywhere in your code. Thus, you probably don't understand how exactly they work. Apparently, you're trying to come up with a custom awaiter , but this is not how it works, either.

You may want to check this question for an example of how to convert the WebBrowser.DocumentCompleted event into a task and await it. Also, the links listed in async-await wiki could help to catch up on the subject.

If you need some more examples of how to use async / await and tasks with WebBrowser , including click automation and web scraping, you may find a lot of them here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM