【问题标题】:C# Form freeze when processing information处理信息时 C# 窗体冻结
【发布时间】:2012-03-14 23:04:53
【问题描述】:

我为自己编写了一个个人网络抓取工具,用于抓取艺术家信息。代码有效,但是当我按下按钮并开始处理 while 循环时,GUI 冻结。我得到了.refresh() 的文本框。但是我不能移动表格,取消程序的唯一方法是强制退出。我正在重写这个,所以我没有遇到这个问题。另外,我听说过踩踏,想看看这是否可行,并让它更快一点。该程序正在抓取 15,000 多个页面,然后每个页面还有另外 10 个左右的页面需要抓取。因此,该程序可能会运行几个小时才能最终完成。

这是我的代码。

        private void btnGet_Click(object sender, EventArgs e)
    {
        int i = 0;
        int maxCount = 15000; //11234 was last value 

        progressBar.Maximum = maxCount;

        while (i <= maxCount)
        {
            txbURL.Text = "http://www.newreleasetuesday.com/albumdetail.php?album_id=" + i;
            label.Text = i.ToString() + " out of " + maxCount.ToString() + " Done.";
            progressBar.Value = i;

            string url = txbURL.Text;

            string sourceCode = sourceCode = WorkerClass.getSourceCode(url);
            int startIndex = sourceCode.IndexOf("//alert(document.getElementById(\"remcheck\").value)");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);

            //Start Artist Name
            //Gets the Artist's ID
            int idCountIndex = sourceCode.IndexOf("  by <a href=\"artistdetail.php?artist_id=") + 41;
            int idCountEndIndex = sourceCode.IndexOf("\">", idCountIndex);
            string artistID = sourceCode.Substring(idCountIndex, idCountEndIndex - idCountIndex) + "";
            txbArtistID.Text = artistID;

            //Gets Artist's Name
            startIndex = sourceCode.IndexOf("  by <a href=\"artistdetail.php?artist_id=") + 43 + artistID.Length;
            int endIndex = sourceCode.IndexOf("</a> | Genre", startIndex);
            string artistName = sourceCode.Substring(startIndex, endIndex - startIndex) + "";
            txbArtist.Text = artistName;
            //End Artist Name

            //Start Album Name
            //Gets Album's ID
            string albumID = url.Substring(url.IndexOf("=") + 1);
            txbAlbumID.Text = albumID;

            //Gets Album's Name
            startIndex = sourceCode.IndexOf("absbottom\"></span></strong> ") + 28;
            endIndex = sourceCode.IndexOf("</span></td>", startIndex);
            string AlbumName = sourceCode.Substring(startIndex, endIndex - startIndex) + "";
            txbAlbum.Text = AlbumName;
            //End Album Name

            //Start Genre
            startIndex = sourceCode.IndexOf("</a> | Genre: ") + 14;
            endIndex = sourceCode.IndexOf(" | ", startIndex);
            string genre = sourceCode.Substring(startIndex, endIndex - startIndex) + "";
            txbGenre.Text = genre;
            //End Genre

            //Start Release Date
            startIndex = sourceCode.IndexOf("<a href=\"releasedate.php?release_date=") + 50;
            endIndex = sourceCode.IndexOf(" </a></td>", startIndex);
            string releaseDate = sourceCode.Substring(startIndex, endIndex - startIndex) + "";
            txbReleaseDate.Text = releaseDate;
            //End Release Date

            //Start Pic URL
            startIndex = sourceCode.IndexOf("<img  src=\"") + 11;
            endIndex = sourceCode.IndexOf("\"  alt=", startIndex);
            string PicURL = sourceCode.Substring(startIndex, endIndex - startIndex) + "";
            PicURL = PicURL.Replace("amp;", "");
            string fullLink = "http://www.newreleasetuesday.com/" + PicURL;
            txbPicURL.Text = fullLink;
            //End Pic URL


            //Refresh UI (Updates textBoxes, labels, and progressBar with new values)
            txbURL.Refresh();
            txbArtist.Refresh();
            txbAlbum.Refresh();
            txbReleaseDate.Refresh();
            txbGenre.Refresh();
            txbPicURL.Refresh();
            txbArtistID.Refresh();
            txbAlbumID.Refresh();
            label.Refresh();
            progressBar.Refresh();

            if (artistName == "")
            {
                // Adding info to Database if there is no artist name
                string cs = "SERVER=asdf.net;" +
                    "DATABASE=music;" +
                    "UID=root;" +
                    "PASSWORD=asdf;";

                MySqlConnection conn = null;

                conn = new MySqlConnection(cs);
                conn.Open();

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "INSERT INTO `emptyalbums` (id, albumid) VALUES('',@albumid)";
                cmd.Prepare();

                cmd.Parameters.AddWithValue("@albumid", albumID);

                cmd.ExecuteNonQuery();
                conn.Close();
            }
            else
            {
                // Adding info to Database if there is an artist name
                string cs = "SERVER=asdf.net;" +
                    "DATABASE=music;" +
                    "UID=root;" +
                    "PASSWORD=asdf;";

                MySqlConnection conn = null;

                conn = new MySqlConnection(cs);
                conn.Open();

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "INSERT INTO `database` (id, artist, album, releasedate, genre, pictureurl, artistid, albumid) VALUES('',@artist, @album, @releasedate, @genre, @pictureurl, @artistid, @albumid)";
                cmd.Prepare();

                cmd.Parameters.AddWithValue("@artist", artistName);
                cmd.Parameters.AddWithValue("@album", AlbumName);
                cmd.Parameters.AddWithValue("@releasedate", releaseDate);
                cmd.Parameters.AddWithValue("@genre", genre);
                cmd.Parameters.AddWithValue("@pictureurl", fullLink);
                cmd.Parameters.AddWithValue("@artistid", artistID);
                cmd.Parameters.AddWithValue("@albumid", albumID);

                cmd.ExecuteNonQuery();
                conn.Close();
            }
            i++;
            
        }

任何信息都会有很长的路要走。 谢谢, 索隆

【问题讨论】:

    标签: c# winforms web-scraping


    【解决方案1】:

    多线程确实是您的问题的解决方案。这里发生的情况是,处理在您的 GUI 线程上启动,一切都冻结了,直到您的循环完成处理。

    多线程的实现将取决于您的框架和您的需求,但如果您使用 .Net 4.0,您可能需要查看 TPL 库。

    http://msdn.microsoft.com/en-us/library/dd460717.aspx

    除此之外,一个关于多线程的简单谷歌搜索将让你立即到达你想去的地方。

    【讨论】:

    • 感谢您的帖子。我对编程还是很陌生。我认为踩踏是我需要走的路。是的,我正在使用 .Net 4.0。
    【解决方案2】:

    当我按下按钮并开始处理 while 循环时,GUI 冻结

    是的,那是因为您违反了 Windows 窗体(以及 WPF 和 Silverlight)的黄金法则之一:

    不要在 UI 线程上做太多工作。

    UI 线程用于处理事件、更新显示等。当您开始使用 SQL 查询等阻止它时,它就无法工作。

    (另一个黄金法则是在 UI 线程上不要触摸 UI 控件除了。)

    有很多方法可以解决这个问题,包括BackgroundWorker。有关更多信息,请参阅 Joe Albahari 的threading tutorial。从根本上说,这个想法是在后台线程上执行非 UI 工作,并在需要更新 UI 时编组回 UI 线程。

    【讨论】:

    • 很高兴知道。谢谢(你的)信息。这真的很有帮助。快速的问题,(仍然是编程新手)踩踏和 BackgroundWorker 是一回事还是 backgroundWorker 是更简单的踩踏版本?
    • backgroudworker 是实现线程的一种方式。我建议你使用它,因为它是最简单的方法,特别是如果你是编程新手
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多