2009-03-04 64 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