2016-02-05 150 views
2

我想停止按鈕點擊事件我的線程,因爲我是新的線程我不知道我怎麼能在C#中做到這一點。我的應用程序是TCP客戶端,我繼續讀取TCP服務器使用此線程停止線程按鈕點擊C#

public void ClientReceive() 
{ 
    try 
    { 

     stream = client.GetStream(); //Gets The Stream of The Connection 
     new Thread(() => // Thread (like Timer) 
     //Thread mythread = new Thread(ClientReceive); 
     { 
      //MessageBox.Show(stream.Read(datalength, 0, 256).ToString()); 
      //(i = stream.Read(datalength, 0, 256)) != 0 
      while (i != 1)//Keeps Trying to Receive the Size of the Message or Data 
      { 
       // how to make a byte E.X byte[] examlpe = new byte[the size of the byte here] , i used BitConverter.ToInt32(datalength,0) cuz i received the length of the data in byte called datalength :D 
       // byte[] data = BitConverter.GetBytes(1000); // Creates a Byte for the data to be Received On 
       byte[] data = new byte[1000]; 
       stream.Read(data, 0, data.Length); //Receives The Real Data not the Size 
       this.Invoke((MethodInvoker)delegate // To Write the Received data 
       { 
        //txtLog.Text += System.Environment.NewLine + "Server : " + Encoding.Default.GetString(data); // Encoding.Default.GetString(data); Converts Bytes Received to String 
        DateTime now = DateTime.Now; 
        //MessageBox.Show(Encoding.Default.GetString(data)); 
        if (Encoding.Default.GetString(data) != "") 
        { 
         txtLog.Text += System.Environment.NewLine + now.ToString() + " Received : \r\n" + Encoding.Default.GetString(data) + "\r\n"; 

        } 
        for (int j = 0; j < txtLog.Lines.Length; j++) 
        { 
         if (txtLog.Lines[j].Contains("Received")) 
         { 
          this.CheckKeyword(txtLog.Lines[j + 1], Color.Red, 0); 
         } 
         if (txtLog.Lines[j].Contains("Sent")) 
         { 
          this.CheckKeyword(txtLog.Lines[j + 1], Color.Blue, 0); 
         } 
        } 

       }); 
      } 
     // mythread.Start(); 
     }).Start(); // Start the Thread 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 
+0

您正在匿名創建線程('new Thread')。如果沒有參考,您無法訪問它。 – Shaharyar

+0

如何在現有代碼中傳遞參考? –

回答

1

試試這個:

Thread thread = new Thread(() => 
    { 
     Console.WriteLine("Some actions inside thread"); 
    }); 
    thread.Start(); 
    thread.Abort(); 

首先,你需要你的線程設置爲某個字段,然後你可以控制它以代碼Start(),Abort()顯示。

如果您想從按鈕單擊事件中取消Abort()線程,您需要將thread字段移出方法,這樣您就可以從按鈕單擊事件中獲取訪問權限。

希望有助於!

+0

Out of Method意思就像這樣public public class Form2:Form { var thread = new Thread(); –

+0

public partial class Form2:Form {Thread thread = new Thread(); – Jamaxack

2

我建議您使用Task而不是Thread。因爲Abort ing線程不推薦,它也可能會影響您的數據。

Eric Lippert很好地解釋了它here

下面是代碼爲您提供:

private CancellationTokenSource tokenSource; //global field 

public void ClientReceive() 
{ 
    try 
    { 
     //initiate CancellationTokenSource 
     tokenSource = new CancellationTokenSource(); 

     stream = client.GetStream(); //Gets The Stream of The Connection 

     //start parallel task 
     Task.Factory.StartNew(() => 
     {   
      //MessageBox.Show(stream.Read(datalength, 0, 256).ToString()); 
      //(i = stream.Read(datalength, 0, 256)) != 0 
      while (i != 1)//Keeps Trying to Receive the Size of the Message or Data 
      { 
       // how to make a byte E.X byte[] examlpe = new byte[the size of the byte here] , i used BitConverter.ToInt32(datalength,0) cuz i received the length of the data in byte called datalength :D 
       // byte[] data = BitConverter.GetBytes(1000); // Creates a Byte for the data to be Received On 
       byte[] data = new byte[1000]; 
       stream.Read(data, 0, data.Length); //Receives The Real Data not the Size 
       this.Invoke((MethodInvoker)delegate // To Write the Received data 
       { 
        //txtLog.Text += System.Environment.NewLine + "Server : " + Encoding.Default.GetString(data); // Encoding.Default.GetString(data); Converts Bytes Received to String 
        DateTime now = DateTime.Now; 
        //MessageBox.Show(Encoding.Default.GetString(data)); 
        if (Encoding.Default.GetString(data) != "") 
        { 
         txtLog.Text += System.Environment.NewLine + now.ToString() + " Received : \r\n" + Encoding.Default.GetString(data) + "\r\n"; 

        } 
        for (int j = 0; j < txtLog.Lines.Length; j++) 
        { 
         if (txtLog.Lines[j].Contains("Received")) 
         { 
          this.CheckKeyword(txtLog.Lines[j + 1], Color.Red, 0); 
         } 
         if (txtLog.Lines[j].Contains("Sent")) 
         { 
          this.CheckKeyword(txtLog.Lines[j + 1], Color.Blue, 0); 
         } 
        } 

       }); 
      } 
     }, tokenSource.Token); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 

//call this method on cancel button 
private void cancelTask() 
{ 
    if(tokenSource != null) //check if its even initialized or not 
     tokenSource.Cancel(); 
} 

如果您需要更多的解釋關於TPL參考this article