0

我的问题涉及事件以及我在课堂上触发事件的位置。这个类包装了我的 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.";
   }
}
4

1 回答 1

0

虽然您没有发布 的​​代码MyTcpClass2,但我很确定我明白您的意思。

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

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

于 2010-11-18T07:43:50.080 回答