Many beginner's friends have encountered this problem when working on projects, that is, the local debugging and running programs are normal and put on the server. However, if some concurrency occurs, you will find that the page cannot be opened. In fact, most of the time it is because the Ado.net link is not fully processed. Of course, this will not happen to laruence.
In fact, it is very easy to avoid this situation and improve the performance of the Connection object. Here we list two methods for beginners or friends who have encountered this problem:
1. Use the try-catch-finally statement block:
SqlConnection conn = new SqlConnection ("link string"); try {conn. open (); // Open the database link // Add some operations on the linked object} catch (SqlException err) {// here error information can be written to the log} finally {conn. close (); // Close the link after the conn object operation is completed} copy the code
The reason for doing so is, although. the. NET Framework has a garbage collection mechanism. However, to ensure the effective use of resources, we need to release them to the resources as soon as possible to ensure that they can be effectively used. At the same time, we do not recommend that you directly use conn after the operation is complete. close () method, because in this case, if the conn will not continue to be executed after an error occurs in this operation, it means that the link will not be closed, and the result is that when you perform the second operation, the link is not closed in the future.
2. You can also use the using statement block:
Using (SqlConnection conn = new SqlConnection ("link string") {conn. Open (); // Add some operations on the Link object} copy the code
If you are interested, you can study the usage of using in C #. Here, using plays a role in no matter how it exits the statement block, will be released to the resources of the conn object.
Of course, my suggestion is that you can use it together, because the using object can ensure the release of resources, while the try statement block can let us capture exceptions and write them to the Log.
From Zhang Jian's column