WebBrowser control throws seemingly random NullReferenceException

前端 未结 1 1005
臣服心动
臣服心动 2020-12-10 09:53

For a couple of days I am working on a WebBrowser based webscraper. After a couple of prototypes working with Threads and DocumentCompleted events, I decided to try and see

相关标签:
1条回答
  • 2020-12-10 10:37

    Busy waiting (while (_wb.IsBusy) ;) on UI thread isn't much advisable. If you use the new features async/await of .Net 4.5 you can get a similar effect (i.e. go to url, perform action, go to other url etc. etc.) you want

    public static class SOExtensions
    {
        public static Task NavigateAsync(this WebBrowser wb, string url)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            WebBrowserDocumentCompletedEventHandler completedEvent = null;
            completedEvent = (sender, e) =>
            {
                wb.DocumentCompleted -= completedEvent;
                tcs.SetResult(null);
            };
            wb.DocumentCompleted += completedEvent;
    
            wb.ScriptErrorsSuppressed = true;
            wb.Navigate(url);
    
            return tcs.Task;
        }
    }
    
    
    
    async void ProcessButtonClick()
    {
        await webBrowser1.NavigateAsync("http://www.stackoverflow.com");
        MessageBox.Show(webBrowser1.DocumentTitle);
    
        await webBrowser1.NavigateAsync("http://www.google.com");
        MessageBox.Show(webBrowser1.DocumentTitle);
    }
    
    0 讨论(0)
提交回复
热议问题