在 C# 中单击按钮时停止线程

本文关键字:线程 按钮 单击 | 更新日期: 2023-09-27 18:33:14

我想在按钮单击事件上停止我的线程,并且由于我是线程新手,我不知道如何在 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());  
    }
}

在 C# 中单击按钮时停止线程

我建议您使用Task而不是Thread。因为不建议Abort线程,它也可能会影响您的数据。

埃里克·利珀特(Eric Lippert)在这里解释得很好。

这是适合您的代码:

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的更多说明,请参阅本文。

试试这个:

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

首先,您需要将线程设置为某个字段,然后可以按照代码Start(),Abort()所示对其进行控制。

如果你想从按钮点击事件中流thread线程,你需要将字段移出方法,这样你就可以从你的按钮点击事件中获得访问权限。

希望有帮助!