2

我正在尝试使用多个线程进行网络请求,但如果我尝试使用超过 2 个线程,我会收到错误

Index was outside the bonds of the array

在这条线上:

string username = ScrapeBox1.Lines[NamesCounter].ToString();

这是代码:

while (working)
{
    while (usernamescount > NamesCounter)
    {
        string username = ScrapeBox1.Lines[NamesCounter].ToString();
        string url = "http://www.someforum.com/members/" + username + ".html";
        var request = (HttpWebRequest)(WebRequest.Create(url));
        var response = request.GetResponse();
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:16.0) Gecko/20100101 Firefox/16.0";

        using (var responseStream = response.GetResponseStream())
        {
            using (var responseStreamReader = new StreamReader(responseStream))
            {

                var serverResponse = responseStreamReader.ReadToEnd();
                int startpoint = serverResponse.IndexOf("Contact Info</span>");
                try
                {
                    string strippedResponse = serverResponse.Remove(0, startpoint);
                    ExtractEmails(strippedResponse);

                }
                catch { }


            }
        }
        NamesCounter++;
        textBox1.Text = NamesCounter.ToString();
    }

}
4

1 回答 1

2

此代码不是线程安全的。

您需要执行 HttpWebRequest 的代码是原子的并且在循环通过集合的上下文之外。

例如

public void MakeHttpWebRequest(string userName)
{
    string url = "http://www.someforum.com/members/" + userName + ".html";
    var request = (HttpWebRequest)(WebRequest.Create(url));
    var response = request.GetResponse();
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:16.0) Gecko/20100101 Firefox/16.0";

    using (var responseStream = response.GetResponseStream())
    {
        using (var responseStreamReader = new StreamReader(responseStream))
        {

            var serverResponse = responseStreamReader.ReadToEnd();
            int startpoint = serverResponse.IndexOf("Contact Info</span>");
            try
            {
                string strippedResponse = serverResponse.Remove(0, startpoint);
                ExtractEmails(strippedResponse);

            }
            catch { }


        }
    }
}

假设 ScrapeBox.Lines 实现了 IEnumerable,我建议使用Parallel.ForEach并将 ScrapeBox.Lines 作为迭代的 IEnumerable 传递。

现在,还有一个问题,从 HttpWebRequest 读取响应的代码仍然需要将其输出写入共享位置。以线程安全的方式实现这一点。一种常见的方法是使用信号量。您需要一个可供每个线程实例访问的对象。类级别的私有变量private object sharedMutex = new object();会起作用。那么代码ExtractEmails(strippedResponse);应该改成 lock(sharedMutex) { ExtractEmails(strippedResponse); }

如果没有该ExtractEmails(<string>)方法的代码,我无法为此提供线程安全的实现,因此部分解决方案可能仍然会导致问题。

于 2012-11-05T00:58:39.027 回答