2013-05-28 35 views
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開始? 我哪裏去錯了?

回答

1

首先,我建議不要爲每個工作項目啓動一個線程。使用Parallel.For而不是自己製作線程。

這不僅會防止錯誤(您可以直接使用索引),但它也會更有效地平衡負載。

這就是說,你的問題是你在每個線程中使用相同的變量。你需要做一個暫時的:

int localIndex; 
lock(SyncIndex) 
{ 
    index++; 
    localIndex = index; // Copy this here, before another thread can change it 
} 

// Use localIndex, not index, from here on... 

在你當前的代碼,您同步指數的增量,但其他線程仍然會「改變」它的價值,然後才能使用它。

+0

你不能在我的代碼上做更多細節?對不起英語 – user2429282

+0

@ user2429282只需將我的代碼換成您的代碼,然後在Run方法中將「index」的每個實例更改爲「localIndex」即可......這將使您的代碼工作變得模糊。這就是說,StackOverflow不是爲了「爲你寫代碼」 - 我們來幫你解答具體的問題,而不是你的工作;) –

+0

好的,謝謝你的幫助。 – user2429282

相關問題