Asynchronus 线程无法与 Async / Await 一起使用

本文关键字:Await 一起 Async 线程 Asynchronus | 更新日期: 2023-09-27 17:56:09

我在Windows Forms项目中有一个WebBrowser控件代码。这工作正常,如下所示。它首先导航到我的 html 页面,然后单击那里的锚标记。每个锚标记将导航到一个网站。

现在,我试图通过添加 async/await 来使其异步。但这行不通。知道这里缺少什么吗?

注意:我无法更改 e1。调用成员("点击"); to webBrowser1.Navigate().因为在我的真实场景中,会有处理导航的 JavaScript 代码。因此,我需要调用 InvokeMember() 本身。

参考

异步等待

C# 代码

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>

Asynchronus 线程无法与 Async / Await 一起使用

现在,我试图通过添加 async/await 来使其异步。但这是不工作。知道这里缺少什么吗?

尽管问题的标题如此,但您不会在代码中的任何位置使用asyncawait关键字。因此,您可能不了解它们究竟是如何工作的。显然,您正在尝试提出一个自定义等待者,但这不是它的工作原理。

您可能需要查看此问题以获取有关如何将WebBrowser.DocumentCompleted事件转换为任务并等待它的示例。此外,维基async-await列出的链接可以帮助赶上这个主题。

如果您需要更多有关如何使用async/await和任务的示例 WebBrowser ,包括点击自动化和网页抓取,您可能会在这里找到很多。