2009-03-04 40 views
0

我有一個相當簡單的web服務,它暴露了來自sql server的數據。它將用於同步2個不同數據庫(SQL Server和Lotus Notes)之間的數據。我們正處於測試Web服務的階段,並以20 req./min。輪詢它,第一個2分鐘就OK了,但在第二個階段後,我們得到一個異常,顯然是連接到數據庫)無法打開(超時)。.NET webservice的性能提示/提示從sql server提供信息

你有什麼建議或建議做什麼或在哪裏看? Web服務已使用C#/ .NET進行編程,在構建(Web服務)對象期間將打開與db的連接,並在對象處置時關閉。

我已經考慮過使用global.asax來「共享」連接,但經過一些Google搜索後,我發現大多數人發現這是一個壞主意,我正在尋找不同的解決方案。

ps。該服務被以同步的方式合併,沒有2個請求在同一時間存在

CNC中 (第一2個anwsers約池後)這是當前的代碼:

public class DataService : System.Web.Services.WebService 
{ 
    private SqlConnection conn = new SqlConnection("Data Source=ip;database=database;uid=user;pwd=secret;"); 
    public DataService() 
    { 
      try 
      { 
       conn.Open(); 

      } 
      catch (Exception dbconn) 
      { 
       throw new SoapException("Couldn't open connection to database:" + dbconn.Message + " More info at: " + dbconn.HelpLink, errorCode); 
      } 
      //Uncomment the following line if using designed components 
      //InitializeComponent(); 
    } 
    ~DataService() 
    { 
     conn.Close(); 
    } 
    [WebMethod(Description="Gets all Person changes(from last week)")] 
    public Person[] GetPerson() 
    { 
      Person[] Personen = null; 
      SqlCommand sqlcmd = conn.CreateCommand(); 

      sqlcmd.CommandText = "SELECT * FROM Person"; 
      SqlDataReader Rows = sqlcmd.ExecuteReader(); 
      while (Rows.Read()) 
      { 
        //doSomething 
      } 

      Rows.Close(); 
      return Personen; 
    } 

}

回答

4

聽起來你已經用盡了連接池 - 最好的選擇是換你的SQL調用使用塊,鬆散這樣的:

using(SqlConnection con = new SqlConnection("MyConnectionString")) 
{ 
    con.Open(); 

    using(SqlCommand cmd = new SqlCommand("MyStoredProcedure", con)) 
    { 
     // Do stuff with the Command 
    } 
} 

這將允許您同時爲連接池的大小提供相同數量的請求。

所以,在您編輯後的代碼變成:

public class DataService : System.Web.Services.WebService 
{ 
    [WebMethod(Description="Gets all Person changes(from last week)")] 
    public Person[] GetPerson() 
    { 
     Person[] Personen = null; 

     using(SqlConnection conn = new SqlConnection("Data Source=ip;database=database;uid=user;pwd=secret;")) 
     { 
      using(SqlCommand sqlcmd = conn.CreateCommand()) 
      { 
       sqlcmd.CommandText = "SELECT * FROM Person"; 
       SqlDataReader Rows = sqlcmd.ExecuteReader(CommandBehavior.CloseConnection); // This will close the DB connection ASAP 
       while (Rows.Read()) 
       { 
        //doSomething 
       } 

       Rows.Close(); 
      } 
     } 

     return Personen; 
    } 
} 
+0

它是否比在對象構造中設置連接好? (我已經添加了一些代碼來闡述)。有沒有辦法在連接之前檢查連接池或以某種方式監視連接池? – Tuxified 2009-03-04 13:20:55