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

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

最佳答案

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

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 .

关于c# - 在 C# 中单击按钮停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216623/

相关文章:

c# - Glass Mapper v4 InferType Cast 问题

c# - 如何在 Razor TextBoxFor 中呈现的 EF Code First 中将小数格式设置为百分比?

c++ - 在单独的线程中处理 vector 元素

multithreading - 为什么自旋锁会成为多线程程序中的性能问题?

android - 处理程序未在辅助线程中加速应用程序

c++ - 线程与进程

c# - 在 ParameterizedThreadStart 中捕获的变量

c# - 我需要互相交换 2 个文件 C#

c# - 如何指定表达式树的返回类型?

c# - 如何从 SQL Server 加载图像到图片框?