c#后台线程

本文关键字:线程 后台 | 更新日期: 2023-09-27 18:03:53

我正在开发一个c# windows软件。我想同时运行6个web浏览器。每个浏览器中都有6个不同的网站导航,我想同时填充它们的值。使用线程,所有浏览器都能正常运行,网站也能正常导航。但我的问题是,价值是一个接一个地填充在每个浏览器。请告诉我如何在每个站点同时填充所有值,以及后台线程(线程在隐藏模式下运行)

frmBrowser  frmBz = new frmBrowser();
void bbyp_com()
{
    frmBrowser1 frmB = new frmBrowser1();
    try
    {
        if (InvokeRequired)
        {
            this.Invoke(new MethodInvoker(bbyp_com));
            return;
        }
        frmB.MdiParent = frmBz;
        frmB.Show();
        frmBz.LayoutMdi(MdiLayout.TileVertical);                
        if (!Navigate(ref frmB.webBrowser1,Global.Website[Global.WebsiteIndex(Global.ListingQueue[5])].urlListing))
            throw new System.ArgumentException("", "");
            frmB.Text = frmB.webBrowser1.Document.Url.ToString();                                  
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["COMPANY"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("BusinessTitle").InnerText);
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["CTYPE"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("Category").SelectSingleNode("CategoryOption1").InnerText);
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["ADDRESS"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Street_Address").InnerText);
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["CITY"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("City").InnerText);
            if (!Global.ComboSelect(frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("select")["ST"], Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("State").InnerText, "Select a state"))
                throw new System.ArgumentException("", "");
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["ZIP"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Zipcode").InnerText);
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["BTN"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Phone").InnerText);
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["WEB_SITE"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Website").InnerText);
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["EMAIL"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("ContactE-Mail").InnerText);
            TimeDelay(1000);
            frmB.webBrowser1.Document.Forms["FrontPage_Form2"].GetElementsByTagName("input")["B1"].InvokeMember("click");
            if (!IsDone(ref frmB.webBrowser1))
                throw new System.ArgumentException("", "");
            frmB.Text = frmB.webBrowser1.Document.Url.ToString();
            TimeDelay(50000);
            if (!Success(ref frmB.webBrowser1, "Thank You!"))
                throw new System.ArgumentException("", "");
            counter--;
            TimeDelay(1000);
            frmB.Close();
        }
        catch (Exception)
        {
            counter--;
            TimeDelay(1000);
            frmB.Close();
            lblFailed.Text = (Convert.ToInt32(lblFailed.Text) + 1).ToString();
        }
    }
第二个函数

    void yellowusa_com()
    {
        frmBrowser1 frmB = new frmBrowser1();
        try
        {                
            if (InvokeRequired)
            {
                this.Invoke(new MethodInvoker(yellowusa_com));
                return;
            }
            frmB.MdiParent = frmBz;
            frmB.Show();
            frmBz.LayoutMdi(MdiLayout.TileVertical);
            if (!Navigate(ref frmB.webBrowser1,Global.Website[Global.WebsiteIndex(Global.ListingQueue[4])].urlListing))
                throw new System.ArgumentException("", "");
            frmB.Text = frmB.webBrowser1.Document.Url.ToString();                           
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["lname"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("BusinessTitle").InnerText);
            TimeDelay(100);
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["comments"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectNodes("Website")[4].SelectSingleNode("Category").InnerText);
            TimeDelay(200);            
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["lContact"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("ContactDetails").SelectSingleNode("Name").SelectSingleNode("FirstName").InnerText + ' ' 
                                                                                                + Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("ContactDetails").SelectSingleNode("Name").SelectSingleNode("LastName").InnerText);
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["lAddress"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Street_Address").InnerText);
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["lCity"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("City").InnerText);
            if (!Global.ComboSelect(frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("select")["lState"], Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("State").InnerText, "- Select"))
               throw new System.ArgumentException("", "");
            string phone = Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Phone").InnerText.Substring(0, 3)
                         + Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Phone").InnerText.Substring(4, 3)
                         + Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Phone").InnerText.Substring(8, 4);
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["lZip"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Zipcode").InnerText);
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["n1Phone"].SetAttribute("value", phone);
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["lEmail"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("ContactE-Mail").InnerText);

            try
            {
                string fax = Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("FaxNumber").InnerText.Substring(0, 3)
                           + Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("FaxNumber").InnerText.Substring(4, 3)
                           + Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("FaxNumber").InnerText.Substring(8, 4);
                frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["lFax"].SetAttribute("value",fax);
            }
            catch (Exception)
            { }
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["websiteURL"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("Website").InnerText);
            frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("textarea")["describeBiz"].SetAttribute("value", Global.XmlData.DocumentElement.SelectNodes("Author")[Global.AuthorDefault()].SelectSingleNode("ClientName").SelectSingleNode("ClientListing").SelectSingleNode("BusinessProfile").SelectSingleNode("BasicCompanyDetails").SelectSingleNode("BusinessDescription").InnerText);
            if (!ShowCaptcha(ref frmB.webBrowser1, "recaptcha"))
                throw new System.ArgumentException("", "");
           string captchaval = objfrmCaptchaSettings.HumanCaptcha();
           frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")["recaptcha_response_field"].SetAttribute("value", captchaval);
           frmB.webBrowser1.Document.Forms["form"].GetElementsByTagName("input")[17].InvokeMember("click");
           if (!IsDone(ref frmB.webBrowser1))
                throw new System.ArgumentException("", "");
           frmB.Text = frmB.webBrowser1.Document.Url.ToString(); 
           if (!Success(ref frmB.webBrowser1, "Thank You"))
                throw new System.ArgumentException("", "");
           counter--;
           TimeDelay(1000);
           frmB.Close();
        }
        catch (Exception)
        {
            counter--;
            TimeDelay(1000);
            frmB.Close();
            lblFailed.Text = (Convert.ToInt32(lblFailed.Text) + 1).ToString();
            Exception();
        }
    }

/*这里的frmBz是MDi的parent

这里我只放了两个函数,因为空间太小

我正在使用这个

Thread m_thread1 = new Thread(new ThreadStart(hotfrog_com));
m_thread1.SetApartmentState(ApartmentState.STA);
Thread m_thread2 = new Thread(new ThreadStart(yahoolocal_com));
m_thread2.SetApartmentState(ApartmentState.STA);
Thread m_thread3 = new Thread(new ThreadStart(ezlocal_com));
m_thread3.SetApartmentState(ApartmentState.STA);
Thread m_thread4 = new Thread(new ThreadStart(merchantcircle_com));
m_thread4.SetApartmentState(ApartmentState.STA);
Thread m_thread5 = new Thread(new ThreadStart(yellowusa_com));
m_thread5.SetApartmentState(ApartmentState.STA);
Thread m_thread6 = new Thread(new ThreadStart(bbyp_com));
m_thread6.SetApartmentState(ApartmentState.STA);

启动线程*选择的网站是列表*

while (selectedwebsites.Count > 0)
{
    try
    {
        if (selectedwebsites[j] == "hotfrog.com")
        {
            counter++;
            m_thread1.Start();
            selectedwebsites.RemoveAt(j);
            break;
        }
        if (selectedwebsites[j] == "local.yahoo.com")
        {
            counter++;
            m_thread2.Start();
            selectedwebsites.RemoveAt(j);
            break;
        }
        if (selectedwebsites[j] == "ezlocal.com")
        {
            counter++;
            m_thread3.Start();
            selectedwebsites.RemoveAt(j);
            break;
         }
         if (selectedwebsites[j] == "merchantcircle.com")
         {
             counter++;
             m_thread4.Start();
             selectedwebsites.RemoveAt(j);
             break;
         }
         if (selectedwebsites[j] == "yellowusa.com")
         {
             counter++;
             m_thread5.Start();
             selectedwebsites.RemoveAt(j);
             break;
         }
         if (selectedwebsites[j] == "bbyp.com")
         {
             counter++;
             m_thread6.Start();
             selectedwebsites.RemoveAt(j);
             break;
         }
     }
     catch(Exception) {}
 }

c#后台线程

为什么要用浏览器呢?难道不能直接向服务器发送HTTP请求吗?浏览器只是提供一个UI,只有当一个"人"应该填写字段在我看来才需要。

在你的情况下,如果你提交数据的网站将你正在填写的表单公开为某种web服务(但这是最好的情况:)),那将是最好的。

下面是在自己的线程中运行Method WebSiteOne的基本知识。我建议你阅读线程,有很多很好的例子可以开始。

Thread threadWebSiteOne = new Thread(new ThreadStart(WebSiteOne));
threadWebSiteOne.Start();

使用BackGroundWorker更新。

BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;  //Gets called when work completed
bw.RunWorkerAsync();
static void bw_DoWork (object sender, DoWorkEventArgs e) {
    //Load Webpage X EG : hotfrog_com();
}

也许你已经添加了一个后台线程,然后在这个线程中逐一打开浏览器?

尝试System.Threading.Threadpool.QueueUserWorkItem(),然后将您的呼叫放到浏览器中。

问题是你的线程根本没有做任何有用的工作,因为它们立即将所有相关的东西编组回UI线程。我在下面缩短了你的代码,使它更容易看到。

void bbyp_com()
{
    frmBrowser1 frmB = new frmBrowser1();
    try
    {
        if (InvokeRequired)
        {
            this.Invoke(new MethodInvoker(bbyp_com));
            return;
        }
        // All of the useful work happens here.
    }
    catch
    {
      // Stuff omitted here for brevity.
    }
}

注意工作线程如何在发生任何实际工作之前立即调用Control.Invoke来递归地重新进入UI线程的方法。在此之上,工作线程实际上等待UI线程在工作线程本身终止之前完成。1的效果比仅仅在UI线程上做所有的事情更糟糕,因为一个新线程已经创建,除了浪费资源之外什么都没有。

天真的解决方案是忽略对工作线程中的Control.Invoke的调用,让它完成所有的工作。但是,唉,这也行不通,因为大多数有用的工作都需要对UI元素做一些事情,正如你可能知道的,这在UI线程之外的任何地方都是被禁止的。

你必须彻底改变你的策略。