我与TcpClient
的{{1}}相关联。现在,Thread
的连接在线程中正确打开,但是TcpClient
的关闭并且线程没有正确发生。我不知道为什么。
这是我开始的主题:
TcpClient
这是 private System.Threading.Thread _thread;
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
_thread = new Thread(DoWork);
_thread.Start();
连接:
TcpClient
现在这里是关闭并重新启动线程的代码private void DoWork()
{
while (!_shutdownEvent.WaitOne(0))
{
try
{
client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse(ip),intport));
//Say thread to sleep for 1 secs.
Thread.Sleep(1000);
}
catch (Exception ex)
{
// Log the error here.
client.Close();
continue;
}
try
{
using (stream = client.GetStream())
{
byte[] notify = Encoding.ASCII.GetBytes("Hello");
stream.Write(notify, 0, notify.Length);
byte[] data = new byte[1024];
while (!_shutdownEvent.WaitOne(0))
{
int numBytesRead = stream.Read(data, 0, data.Length);
if (numBytesRead > 0)
{
line= Encoding.ASCII.GetString(data, 0, numBytesRead);
}
}
...
:
TcpClient
请帮我停止并正确启动帖子 _shutdownEvent.WaitOne(0);
_thread.Abort();
//Start Again
_thread = new Thread(DoWork);
_thread.Start();
。
感谢。
答案 0 :(得分:0)
将_shutdownEvent声明为AutoResetEvent。
AutoResetEvent _shutdownEvent = new AutoResetEvent(false);
删除Dowork方法中的外部while循环
private void DoWork()
{
try
{
client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse(ip), intport));
//Say thread to sleep for 1 secs.
Thread.Sleep(1000);
}
catch (Exception ex)
{
// Log the error here.
client.Close();
return;
}
try
{
using (stream = client.GetStream())
{
byte[] notify = Encoding.ASCII.GetBytes("Hello");
stream.Write(notify, 0, notify.Length);
byte[] data = new byte[1024];
while (!_shutdownEvent.WaitOne(0))
{
int numBytesRead = stream.Read(data, 0, data.Length);
if (numBytesRead > 0)
{
line = Encoding.ASCII.GetString(data, 0, numBytesRead);
}
}
}
}
catch
{
}
finally
{
if (stream != null)
stream.Close();
if (client != null)
client.Close();
}
}
使用_shutdownEvent.Set()
表示事件。
_shutdownEvent.Set(); //Set, not Wait
//_thread.Abort(); //and you don't have to abort the thread since it will end gracefully after it break out of the while loop
while (_thread.IsAlive) ; //wait until the first thread exit
//Start Again
_thread = new Thread(DoWork);
_thread.Start();