我有100多个这样的方法,每个方法被调用超过一千次。 这里每次调用都会创建一个新的SqlConnection)(取自池)。 虽然这些方法很小并且控制立即离开了方法,但是应该由GC收集SqlConnection。
Method() { MyComponent adapter = new MyComponent (); adapter.Connection = GetConnection(dbContext);//Here I get new SqlConnection adapter.Update(_SqlTable);} //方法结束
我的问题是 - 以下优化是否有任何区别?
Method(){ MyComponent adapter = new MyComponent (); adapter.Connection = GetConnection(dbContext);//Here I get new SqlConnection adapter.Update(_SqlTable); adapter.Connection.Close() // Or Dispose() } //End of Method有没有更好的方法来编写这些方法(例如,使它们成为静态静态方法)
I have 100s of such methods and each method is called more than thousand times. Here with each call a new SqlConnection is created)(taken from pool). Though the methods are small and control immediately leaves the method and SqlConnection is supposed to be collected by GC.
Method() { MyComponent adapter = new MyComponent (); adapter.Connection = GetConnection(dbContext);//Here I get new SqlConnection adapter.Update(_SqlTable);} //End of Method
My question is - Does the following optimization makes any difference ??
Method(){ MyComponent adapter = new MyComponent (); adapter.Connection = GetConnection(dbContext);//Here I get new SqlConnection adapter.Update(_SqlTable); adapter.Connection.Close() // Or Dispose() } //End of MethodIs there any better way to write these methods (e.g make them static static methods )
最满意答案
是的,你应该绝对关闭连接而不是让它最终完成。 您是否正在尝试编写自己的连接池? 如果是这样,请不要 - 框架自动提供它。 只需创建一个新的SqlConnection ,它将从池中获取底层连接。
您应该使用using语句来确保无论发生什么情况都要处理连接:
using (SqlConnection connection = GetConnection(dbContext)) { MyComponent adapter = new MyComponent(connection); adapter.Update(_SqlTable); }您应该记录MyComponent在这种情况下不对连接的生命周期负责。 另一种方法是使MyComponent实现IDisposable ,将它传递给构造函数中的数据上下文,并处理掉:
using (MyComponent adapter = new MyComponent(dbContext)) { adapter.Update(_SqlTable); }在不知道MyComponent作用的情况下,很难提供更多的设计建议。
Yes, you should absolutely close a connection rather than just letting it get finalized. Are you trying to write your own connection pooling? If so, don't - the framework provides it automatically. Just create a new SqlConnection and it will take the underlying connection from a pool.
You should use a using statement to make sure the connection is disposed whatever happens:
using (SqlConnection connection = GetConnection(dbContext)) { MyComponent adapter = new MyComponent(connection); adapter.Update(_SqlTable); }You should document that MyComponent does not take responsibility for the lifetime of the connection in this case. An alternative would be to make MyComponent implement IDisposable, pass it the data context in the constructor, and dispose of that:
using (MyComponent adapter = new MyComponent(dbContext)) { adapter.Update(_SqlTable); }It's hard to give much further design advice without knowing what MyComponent does.
更多推荐
发布评论