VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • thread中使用await,abort触发异常?

如题,自己做小工具,面向单个socket的tcp连接,使用thread处理TcpListener以及后续的数据接收,中间用到了await 和AcceptSocketAsync,然后我想在正在等待的时候取消listener状态。
目前使用的方式为直接thread.abort
但是在捕获到System.ObjectDisposedException
大致是说System.Net.Socket对象在企图对ta执行Dispose的时候已经被释放..

补充代码描述:

internal class TcpServer_view_module : INotifyPropertyChanged
{
 ...
  private TcpListener tcp_listener = null;
  private Socket tcp_socket = null;
 ...
  private async void thread_process_tcp_listener()
  {
    try
    {
      while (true)
      {
        state = state_tcp_serve.waiting_client;
        tcp_listener.Start(1);
        tcp_socket = await tcp_listener.AcceptSocketAsync();
        tcp_listener.Stop();
        state = state_tcp_serve.connected;

        if (tcp_socket != null)
        {
          while (true)
          {
            byte[] buffer = new byte[2048];
            int len = tcp_socket.Receive(buffer);
            if (len == 0)
            {
              //socket disconnect
              tcp_socket.Dispose();
              break;
            }
            else
            {
              DataReceived(buffer, len);
            }
          }
        }
      }
    }
    catch (System.ObjectDisposedException dispose_e)
    {
 ...
    }
    catch (SystemException se)
    {
 ...
      state = state_tcp_serve.not_started;
    }
  }

 ...
  private void on_click()
  {
    switch (state)
    {
      case state_tcp_serve.not_started:
 ...
        thread_listener = new Thread(new ThreadStart(thread_process_tcp_listener));
        thread_listener.Start();
        break;

      case state_tcp_serve.waiting_client:
        tcp_listener.Stop();
        if (thread_listener != null)
        {
          thread_listener.Abort();
        }
        if (tcp_socket != null)
        {
          tcp_socket.Dispose();
          tcp_socket = null;
        }
        state = state_tcp_serve.not_started;
        break;

      case state_tcp_serve.connected:
        state = state_tcp_serve.not_started;
        if (thread_listener.IsAlive)
        {
          thread_listener.Abort();
        }
        if (tcp_socket != null)
        {
          tcp_socket.Dispose();
          tcp_socket = null;
        }
        break;
    }
  }
}


相关教程