2008-10-15 39 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對象,這可能是這裏發生的事情。

希望這會流露出一些光芒。