2016-02-05 237 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