gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:51:48 27 4
gpt4 key购买 nike

我想在按钮单击事件时停止我的线程,由于我是线程的新手,我不知道如何在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com