控制台应用程序:在STA线程内运行的类中运行WebBrowser

时间:2016-04-04 11:48:14

标签: c# multithreading webbrowser-control console-application

我创建了一个使用WebBrowser控件来删除一些文本数据的类,它最初在Windows窗体应用程序中运行,现在我将其转换为控制台应用程序,为此我在一个线程中运行我的类,在STA中设置它,然后在我的类中我使用" new"以正常方式实例化WebBrowser。关键字,我的问题是当线程完成时它永远不会真正结束,当我使用Thread.Join()时,我进入无休止的等待,如果我使用Application.ThreadExit()没有任何反应,所以我尝试了Thread.Abort(),并且这样可以随机抛出异常,我的问题是运行需要在Console应用程序中实例化WebBrowser的类的正确方法。

这就是我为班级创建线程的方法:

var th = new Thread(() =>
{
    var br = MyBrowsingClass;
    br.NavigateTo(url);
    System.Windows.Forms.Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
return th;

在课堂上我做了以下几点:

wb = new WebBrowser();
wb.ScriptErrorsSuppressed = true;
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(OnWebComplete);
CurrentState = Status.Navigating;
if (IsValidURL(GoogleQueryURL))
{
    wb.NavigateTo(GoogleQueryURL);
}

1 个答案:

答案 0 :(得分:0)

您应该使用WebRequest类,因为我认为您需要内容而不是交互式浏览器。这将消除使用带有额外线程的消息泵(Application.Run())。

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL.        
            WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            // Display the status.
            Console.WriteLine (response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Cleanup the streams and the response.
            reader.Close ();
            dataStream.Close ();
            response.Close ();
        }
    }
}
来自msdn的

SOURCE

https://msdn.microsoft.com/en-us/library/system.net.webrequest%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396