.NET, the SqlConnection object, and multi-threading

前端 未结 2 785
旧巷少年郎
旧巷少年郎 2020-12-11 02:29

We have an application which uses an SQL Server 2008 R2 database. Within the application, calls to the database are made using a SqlConnection object.

T

2条回答
  •  醉酒成梦
    2020-12-11 02:53

    I see no reason NOT to create a SQL connection every time you need it. In fact, that is probably the best way to do it because it gives the .NET framework the flexibility to manage and reuse connections most efficiently. Wrap each of your SQL connections in a USING so you hang on to them as short a time as possible.

    We've created a method that creates a connection and everyone uses that:

    using (var conn = GetConnection())
        using (var proc = GetProcedure(conn, "procname"))
            using (var reader = proc.GetReader())
            {
                ... DB stuff
            }
    

提交回复
热议问题