来自c#中AsyncCallback的触发事件

时间:2010-11-18 07:14:06

标签: c# events controls tcplistener asynccallback

我的问题涉及事件以及我在课堂上触发事件的地方。这个类包装了我的TCP功能,我使用TcpListener来实现这一点。我意识到以下示例中可能缺少一些TCP内容,但我希望尽可能简单:

c#2.0示例

class MyTcpClass
{
   public delegate void ClientConnectHandler(Socket client, int clientNum);

   public event ClientConnectHandler ClientConnect;

   private Socket wellKnownSocket;
   private Socket[] clientSockets = new Socket[MAX_CLIENTS];
   private int numConnected = 0;

   private void OnClientConnect(Socket client, int clientNum)
   {
      if (ClientConnect != null)
         ClientConnect(client, clientNum);
   }

   public void StartListening()
   {
      //initialize wellKnownSocket
      //...
      wellKnownSocket.BeginAccept(new AsyncCallback(internal_clientConnect);
   }

   public void internal_clientConnect(IAsyncResult ar)
   {
      //Add client socket to clientSocket[numConnected]
      //numConnected++;
      //...
      wellKnownSocket.EndAccept(ar);

      OnClientConnect(clientSocket[numConnected], numConnected);          
      //error: event happens on different thread!!
   }
}

class MainForm
{
   void Button_click()
   {
      MyTcpClass mtc = new MyTcpClass();
      mtc.ClientConnect += mtc_ClientConnected;
   }

   void mtc_clientConnected(Socket client, int clientNum)
   {
      ActivityListBox.Items.Add("Client #" + clientNum.ToString() + " connected.");
      //exception: cannot modify control on seperate thread
   }
}

我想我的问题是,在不破坏这种模式的情况下,更有意义的是什么?此外,如果有人有更好的更优雅的解决方案,欢迎他们。

理论

class MainForm
{
   public MainForm()
   {
      MyTcpClass mtc = new MyTcpClass();
      MyTcpClass2 mtc2 = new MyTcpClass2(this);  
      //this version holds a Form handle to invoke the event

      mtc.ClientConnect += mtc_uglyClientConnect;
      mtc2.ClientConnect += mtc2_smartClientConnect;
   }

   //This event is being called in the AsyncCallback of MyTcpClass
   //the main form handles invoking the control, I want to avoid this
   void mtc_uglyClientConnect(Socket s, int n)
   {
      if (mycontrol.InvokeRequired)
      {
         //call begininvoke to update mycontrol
      }
      else
      {
         mycontrol.text = "Client " + n.ToString() + " connected.";
      }
   }

   //This is slightly cleaner, as it is triggered in MyTcpClass2 by using its
   //passed in Form handle's BeginInvoke to trigger the event on its own thread.
   //However, I also want to avoid this because referencing a form in a seperate class
   //while having it (the main form) observe events in the class as well seems... bad
   void mtc2_smartClientConnect(Socket s, int n)
   {
      mycontrol.text = "Client " + n.ToString() + " connected.";
   }
}

1 个答案:

答案 0 :(得分:0)

虽然您没有发布MyTcpClass2的代码,但我很确定我会看到您的内容。

不,我不会第二种方式。因为,例如,如果其他任何东西需要同时绑定到该事件,您将强制它在另一个线程上运行。

简而言之,接收事件的方法应该负责在需要的任何线程上运行它需要的任何代码。引发事件的机制应完全忽略接收器所需的任何奇怪的线程化内容。除了使多事件绑定方案复杂化之外,它还将跨线程调用的逻辑移动到不属于它的类中。 MyTcpClass类应该专注于处理TCP客户端/服务器问题,而不是使用Winforms线程。