2008-10-15 40 views
0

我有一个TcpClient的字段的抽象基类: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等...他们是必需的f或非常特定的硬件通信协议,但这不是这个问题的一部分。

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

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的)似乎被处置,所以创建一个新的连接方法,并再次调用连接方法,真的减慢了通信过程。

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

如SetDevicePower(字节功率电平),QueryDeviceName()等...

代码如此:

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

使连接方法被调用两次......为什么它被在呼叫之间放置?

回答

0

“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); 
    } 

其次,赶上(例外)也是一个坏主意,你不能假设的例外是超时,因为在这里应该捕捉到许多其他异常。

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

希望这会流露出一些光芒。