我試圖使多線程webrequests,但如果我有超過2試試我得到錯誤C#錯誤
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();
}
}
你的代碼顯然不是線程安全的。你認爲會發生什麼? –
是的,但我不想在整個方法上使用鎖,因爲這會使多線程無意義。如果我只把一個鎖放在NamesCounter上,我仍然會得到相同的錯誤 –
你(可能)不需要在整個方法上保持鎖定,只需要那些將被多個線程訪問的變量... –