我有一个带有TcpClient字段的抽象基类:

public abstract class ControllerBase
{
    internal protected TcpClient tcpClient;

它有一种设置连接的方法:

private void setupConnection(IPAddress EthernetAddress, ushort TcpPort)
    {
        if (this.tcpClient == null || !this.tcpClient.Connected)
        {
            this.tcpClient = new TcpClient();

            try
            {
                this.tcpClient.Connect(EthernetAddress, TcpPort);
            }
            catch(Exception ex)
            {
                throw new TimeoutException("The device did not respond.\n" + ex.Message);
            }
        }
    }

而不是请求数据的方法:

 internal protected virtual byte[] requestData(IPAddress EthernetAddress, ushort TcpPort, byte[] data, bool IgnoreResponse)
    {
        setupConnection(EthernetAddress, TcpPort);

        //The rest of the code uses this.tcpClient 

还有一些其他的,例如requestRawData等......它们是非常特定的硬件通信协议所必需的,但这不是任何方式的问题的一部分。

然后我有从这个类派生的类,它们覆盖基类方法:

public class Controller : ControllerBase
{
  internal virtual byte[] requestData(byte[] data, bool IgnoreResponse)
  {
        return base.requestData(this.eth0.EthernetAddress, this.eth0.TcpPort, data, IgnoreResponse);
  }

代码无异常地工作,但每次调用setupConnection方法时, 似乎处理了TcpClient实例(tcpClient),因此创建了一个新实例并再次调用connect方法,这确实减慢了通信过程。

注意:子类的公共方法调用requestData方法, 使用此库从开发人员中抽象出许多细节。

如SetDevicePower(字节PowerLevel),QueryDeviceName()等......

这样的代码:

Controller controller = new Controller("172.17.0.3",34000);
string name = controller.QueryDeviceName();
controller.SetDevicePower(200);

导致connect方法被调用两次...为什么要在调用之间进行处理?

有帮助吗?

解决方案

“setupConnection”中存在一些效率低下的问题。您可能想要研究的方法。第一个问题是你在TcpClient关闭时实例化它。这不是必需的。我会将空检查和连接逻辑拆分为2个方法,或者方法中至少有两个代码块:

  if (this.tcpClient == null)
  {
    this.tcpClient = new TcpClient();
  }

  try
  {
    if (!this.tcpClient.Connected)
    {
      this.tcpClient.Connect(EthernetAddress, TcpPort);
    }
  }
  catch(Exception ex)
  {
    throw new TimeoutException("The device did not respond.\n" + ex.Message);
  }

其次,catch(Exception)也是一个坏主意,你不能认为异常是超时,因为这里应该捕获许多其他异常。

至于你的答案:你可能需要在requestData方法中提供进一步的实现细节,因为那里可能有一个线索。例如,您关闭了连接吗?如果是这样,你最后会在下次调用setupConnection时创建一个新的TcpClient对象,这可能就是这里发生的事情。

希望这会有所启发。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top