在C#中创造新的SqlConnection架空 [英] Overhead of creating new SqlConnection in c#

查看:156
本文介绍了在C#中创造新的SqlConnection架空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前阵子我写了一个ORM层为我的.net应用程序中,所有的数据库行再由 DatabaseRecord 的子类psented $ P $。有许多像方法加载()保存()等。在我最初的实现我创建了一个连接到数据库中 DatabaseRecord 例如

A while back I wrote an ORM layer for my .net app where all database rows are represented by a subclass of DatabaseRecord. There are a number of methods like Load(), Save() etc. In my initial implementation I created a connection to the DB in the constructor of DatabaseRecord e.g.

connection = new SqlConnection(
    ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);

我然后调用打开()关闭()上的SqlConnection我的方法,在开始和结束其访问数据库。这似乎对我(的人谁是熟悉的编程,但新C#和.NET)是最有效的方式做事情 - 有一个连接,并打开/在必要时类中关闭它

I then call Open() and Close() on that SqlConnection at the beginning and end of my methods which access the database. This seemed to me (as someone who was familiar with programming but new to c# and .net) to be the most efficient way to do things - have one connection and open/ close it where necessary within the class.

我刚刚做虽然有些阅读和看来,这种模式建议在一些地方:

I've just been doing some reading though and it appears that this pattern is recommended in a number of places:

using (var connection = new SqlConnection(...)) {
    connection.Open();
    // Stuff with the connection
    connection.Close();
}

我可以看到为什么它的可取 - 连接自动为的Dispose() D,即使你在中间做的东西,会导致未捕获的异常。我只是想知道的开销是调用新的SqlConnection()可能很多次这样的。

I can see why it's desirable - the connection is automatically Dispose()d even if the stuff you do in the middle causes an uncaught exception. I was just wondering what the overhead is for calling new SqlConnection() potentially many times like this.

连接池,所以我想象中的开销是最小的,第二个方法应该是最好的做法,但我只是想确保我的假设是正确的。

Connection Pooling is on so I imagine the overhead is minimal and the second approach should be best practice but I just wanted to make sure my assumptions are right.

推荐答案

是的,这是最好的做法。该使用让您调用close()异常安全。

Yes, it is best practice. The using makes your call to Close() exception-safe.

和创建(任何)对象的开销确实是最小的,并且最小的为短命的对象(即留在GC一代0)。

And the overhead of creating a (any) object is indeed minimal, and smallest for short-lived objects (that stay in GC generation 0).

请注意,您不必再调用Close()在使用块结束时,它会自动为你做(处置==关闭)。

Note that you don't have to call Close() at the end of the using-block anymore, it is automatically done for you (Dispose==Close).

这篇关于在C#中创造新的SqlConnection架空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆