.NET State of DB Connection

↘锁芯ラ 提交于 2019-12-21 17:01:58

问题


When you manage database connection manually you always open and close it. Sometimes you need to check if connection has some state before do some action. A classic situation is check for not Closed state before close connection. Something like

if (connection.State != ConnectionState.Closed)
    connnection.Close();

As MSDN states the ConnectionState is enum WITH FLAGS. It means that connection state can have different states at same time. May be Broken+Closed or something else...

If you decompile System.Data.ConnectionState enum you will see

[Flags]
public enum ConnectionState
{
    Closed = 0,
    Open = 1,
    Connecting = 2,
    Executing = 4,
    Fetching = 8,
    Broken = 16,
}

The value of Closed item is ZERO. It means that following is always true:

connection.State.HasFlag(ConnectionState.Closed)

So. Any suggestions why does this enum have Flags attribute? Or (if this enum must be Flags) why does Closed item have 0 value?


回答1:


I believe in the original .NET 1.1 implementation they planed on making it a flags based enum, However I don't think that is how the current implementation is used if you look at the note in the remarks section

Note:
The values in this enumeration are not designed to be used as a set of flags.

You don't need to check for flags it is safe to do a direct == test. They did not remove the Flags attribute because it would break binary compatibility with .NET 1.1 which they won't do.




回答2:


The [Flags] attribute on an enum allows you to assign multiple values to your enum at once, which is not possible otherwise. You can do this with bitwise manipulations, meaning you can store an enum with A and C set (both at once), not just A and not just C.

In this case it may sometime mean that the ConnectionState is Open and Executing.

The value of Closed is assigned zero so that it may not ever mean that the ConnectionState is Closed as well as Open.

This post will provide more clarifications on this matter.




回答3:


Zero means that nothing is selected. In case of Open 00001, In case Of Connecting 00010, In case of Open AND Connection 00011 ....

0 0 0 0 0 
B F E C O 

Open = 1,
Connecting = 2,
Executing = 4,
Fetching = 8,
Broken = 16,


来源:https://stackoverflow.com/questions/35483542/net-state-of-db-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!