2014-09-30 3 views
1

Я подключен к TcpClient с помощью Thread. Теперь соединение TcpClient правильно открывается в потоке, но закрытие TcpClient и Thread происходит неправильно. Я не знаю, почему ..Как закрыть 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); 
       } 
      } 
      ... 

и теперь вот код, чтобы закрыть и resstart Нить и TcpClient ..

_shutdownEvent.WaitOne(0); 
_thread.Abort(); 

//Start Again 
_thread = new Thread(DoWork); 
_thread.Start(); 

Пожалуйста, помогите мне, чтобы остановить и запустите Thread и TcpClient правильно. Спасибо ..

ответ

0

Объявление _shutdownEvent как AutoResetEvent.

AutoResetEvent _shutdownEvent = new AutoResetEvent(false); 

Удалите внешнюю петлю в то время как в методе DoWork

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(); 
+0

Это так же, как, вероятно, чтобы убить новую нить :) –

+0

Я не могу перезапустить 'TcpClient();' клиент с данным кодом –

+0

'_thread = новая тема (DoWork); _thread.Start(); 'с этим кодом я не могу получить точку останова в методе Dowork(). –

Смежные вопросы