【发布时间】:2014-11-24 14:42:17
【问题描述】:
我通过Thread 连接到TcpClient。现在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();
请帮助我正确停止和启动线程和TcpClient。
谢谢。
【问题讨论】:
标签: c# multithreading sockets tcp tcpclient