停止按钮上的线程单击C#

时间:2016-02-05 05:05:36

标签: c# multithreading

我想在按钮点击事件上停止我的线程,因为我是线程新手,我不知道如何在C#中执行此操作。我的应用程序是TCP客户端,我正在使用此线程连续读取TCP服务器

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());  
    }
}

2 个答案:

答案 0 :(得分:2)

我建议您使用Task代替Thread。因为Abort线程不会被推荐,也可能会影响您的数据。

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

答案 1 :(得分:1)

试试这个:

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

首先,你需要将你的线程设置为某个字段然后你可以控制它,如代码,Start(),Abort()所示。

如果您希望从按钮点击事件中删除Abort()线程,则需要将thread字段移出方法,这样您就可以通过按钮点击事件进行访问。

希望帮助!