如何正确调用委托 [英] How to properly invoke a delegate

查看:118
本文介绍了如何正确调用委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TCPServer类,该类坐在并侦听指定端口上的客户端连接.当客户端向服务器发送数据时,该类读取字节并引发事件以将可用数据通知订阅者.

I have a TCPServer class that sits and listens on a specified port for clients to connect. When a client sends data to the server, the class reads the bytes and raises an event to notify subscribers of the available data.

 

我不想简单地同步引发该事件,因为这会在高流量时间内导致性能问题.但是,当我使用BeginInvoke/EndInvoke模式引发事件时,我的应用程序线程数不断攀升. 而且它们似乎从未被收集.

I dont want to simply raise the event synchronously as this causes performance issues during high traffic times. However, when I use the BeginInvoke/EndInvoke pattern to raise the event, my applications thread count keeps climbing and climbing and climbing and they never seem to be collected.

 

我的代码如下:

 


private void OnDataReceived(System.Net.Sockets.TcpClient client, byte[] data)
  {
   if (DataReceived != null)
   {
    DataReceived.BeginInvoke(client, data, new AsyncCallback(AsyncCallBack), null);
   }
  }

  private void AsyncCallBack(IAsyncResult result)
  {
   try
   {
    AsyncResult asyncResult = result as AsyncResult;
    (asyncResult.AsyncDelegate as TcpDataReceivedEventHandler).EndInvoke(result);
   }
   catch (Exception)
   {
    // Whoops
   }
  }

推荐答案

"我的应用程序线程数不断攀升和攀岩,它们似乎从未被收集."

"my applications thread count keeps climbing and climbing and climbing and they never seem to be collected."

您需要确保您的应用程序线程即将结束,可能会收到未处理的异常,请确保执行以下操作:

You need to be sure your app thread is ending, probly you getting a unhandled exception, make sure you do:

MyAppThread()

MyAppThread()

{

 尝试{

    ...在这里做所有的事情

    ... do all stuff here

  }

  catch(异常例外)

  catch(Exception ex)

   Log(ex);

    Log(ex);

  }

返回;

}


这篇关于如何正确调用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆