DataReader Link Close FAQ

Source: Internet
Author: User

I have seen some posts: questions about DataReader's closure, which may seem confusing to everyone. I will explain it here:

No matter what xxDataReader is, It inherits the implementation of DataReader, so there are commonalities, so the title is titled DataReader.

Case 1: The default link of DataReader is not closed.

Sample Code:

 
 
  1. static void Main(string[] args)  
  2. {  
  3.     SqlConnection con = new SqlConnection("server=.;database=MySpace;uid=sa;pwd=123456");  
  4.     con.Open();  
  5.     SqlCommand com = new SqlCommand("select top 1 id from blog_user",con);  
  6.     SqlDataReader sdr = com.ExecuteReader(System.Data.CommandBehavior.CloseConnection);  
  7.     while (sdr.Read())  
  8.     {  
  9.     }  
  10.     Console.WriteLine(sdr.IsClosed);  
  11.     Console.WriteLine(con.State.ToString());  
  12.     Console.ReadLine();  

Conclusion:

False

Open

Note: whether or not System. Data. CommandBehavior. CloseConnection is added by default, the database link will not be disabled during reading.

Scenario 2: The DataReader link is closed.

Sample Code: [the original code]

 
 
  1. protected void bind()  
  2. {  
  3.     SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());  
  4.     conn.Open();  
  5.     SqlCommand cmd = new SqlCommand("GetAllUser", conn);  
  6.     SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
  7.     repeater1.DataSource = sdr;  
  8.     repeater1.DataBind();  
  9.     Response.Write(sdr.IsClosed.ToString() + "<br/>");  
  10.     Response.Write(conn.State.ToString());  
  11. }  

The result is:

Required True

 Closed

Situation: After System. Data. CommandBehavior. CloseConnection is added, the link is closed for you. Why? See the cause of the analysis below.

Iii. Cause Analysis

1: from the two examples above, what is the difference?

A: The difference is that one is read-only data and the other is bound with a data list control.

2: Why does the link automatically close when a data list control is bound?

A: This involves the Data Control binding mechanism. Here is a brief introduction:

A: To bind the data control list, an interface is required: IEnumerable

B: code that implements DataReader to implement this interface [the base class is an abstract method, so it can only be viewed by the subclass SqlDataReader]:

 
 
  1. public override IEnumerator GetEnumerator()  
  2. {  
  3.     return new DbEnumerator(this, (this._commandBehavior & CommandBehavior.CloseConnection) ==     CommandBehavior.CloseConnection);  
  4. }  

From this code, we can see that it has passed CloseConnection into DbEnumerator, and then we can see it again:

 
 
  1. Public DbEnumerator (IDataReader reader, bool closeReader)
  2. {
  3. If (reader = null)
  4. {
  5. Throw ADP. ArgumentNull ("reader ");
  6. }
  7. This. _ reader = reader;
  8. This. closeReader = closeReader; // The flag is set for this row.
  9. }

Click it to view the constructor and assign it to this. closeReader attribute. Because DataReader is a forward read method, the focus is to look at MoveNext:

 
 
  1. Public bool MoveNext ()
  2. {
  3. If (this. _ schemaInfo = null)
  4. {
  5. This. BuildSchemaInfo ();
  6. }
  7. This. _ current = null;
  8. If (this. _ reader. Read () // this method is called once and Read once
  9. {
  10. Object [] values = new object [this. _ schemaInfo. Length];
  11. This. _ reader. GetValues (values );
  12. This. _ current = new DataRecordInternal (this. _ schemaInfo, values, this. _ descriptors, this. _ fieldNameLookup );
  13. Return true; // return directly if data exists. The following close link is not executed.
  14. }
  15. If (this. closeReader) // well, you can proceed here. It indicates that no data has been read. In short, the data has been read.
  16. {
  17. This. _ reader. Close (); // Close the link.
  18. }
  19. Return false;
  20. }

The above code is described in my comments.

C: Why is it difficult to bind a list control with DataReader?

A: Because the server control list usually takes a long time to render the table, the last row of data is read only when you see the final result list.

Therefore, the link is open for a long time. Therefore, when there are many concurrent web connections, an error is returned when the connection pool is full.

4. What is the final conclusion?

1: When a list control is bound, the link is automatically closed once the data row is read.

2: When you directly read data, it does not trigger binding related reads, so the link is not automatically closed.

3.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.