我有一个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);
使连接方法被调用两次......为什么它被在呼叫之间放置?