1
來自文本文件的多線程柵欄行,然後在收到寫入另一個文本文件的肯定響應後發送請求表單post \ get數據。如何同步並將所有內容寫入文本?
public int index = -1;
public int count = 1000;
private static readonly object SyncIndex = new object();
private static readonly object SyncFiles = new object();
public void CreateThreads(int threads)
{
Thread[] threadArray;
for (int i = 0; i < (threadArray = new Thread[threads]).Length; i++)
{
threadArray[i] = new Thread(this.Run) { IsBackground = true };
threadArray[i].Start();
}
}
public void Run()
{
while (true)
{
lock(SyncIndex) { index++;}
//if (index > count) { break; }
string resp = Check(index.ToString());
lock (SyncFiles)
{
if (resp == "true")
{
SaveText("good.txt", index.ToString());
}
else
{
SaveText("bad.txt", index.ToString());
}
}
}
}
public string Check(string login)
{
try
{
System.Net.WebRequest reqGET = System.Net.WebRequest.Create(@"http://www.minecraft.net/haspaid.jsp?user=" + login);
System.Net.WebResponse resp = reqGET.GetResponse();
System.IO.Stream stream = resp.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
string s = sr.ReadToEnd();
if (s.Contains("true"))
{
return "true";
}
else
{
return "false";
}
}
catch
{
Check(login);
}
return "";
}
//static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
private static void SaveText(string file, string text)
{
//cacheLock.EnterWriteLock();
try
{
var write = new StreamWriter(file, true);
write.WriteLine(text);
write.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//finally
//{
// cacheLock.ExitWriteLock();
//}
}
private void btStart_Click(object sender, EventArgs e)
{
CreateThreads(300);
}
什麼問題? 數= 1000個 線程= 300
bad.txt
299
300
301
302
303
304
305
306
307
308
310
311
312
313
314
315
316
good.txt
309
爲什麼文本,然後在300開始? 我哪裏去錯了?
你不能在我的代碼上做更多細節?對不起英語 – user2429282
@ user2429282只需將我的代碼換成您的代碼,然後在Run方法中將「index」的每個實例更改爲「localIndex」即可......這將使您的代碼工作變得模糊。這就是說,StackOverflow不是爲了「爲你寫代碼」 - 我們來幫你解答具體的問題,而不是你的工作;) –
好的,謝謝你的幫助。 – user2429282