Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
nó không phải là một quy luật chung. Bạn cần đo lường hiệu suất để xác định nếu bạn có một trường hợp cụ thể nơi mà các cấu trúc truy vấn không thực hiện cũng đủ. Tuy nhiên, trước khi viết lại hoàn toàn một thuật toán, xem xét các phần mở rộng song song cho LINQ. | 90 I Chapter 2 .Net Resource Management finally myConnection.Dispose If you use the using statement with a variable of a type that does not support the IDisposable interface the C compiler generates an error. For example Does not compile String is sealed and does not support IDisposable. using string msg This is a message Console.WriteLine msg The using statement works only if the compile-time type supports the IDisposable interface. You cannot use it with arbitrary objects Does not compile. Object does not support IDisposable. using object obj Factory.CreateResource Console.WriteLine obj.ToString A quick defensive as clause is all you need to safely dispose of objects that might or might not implement IDisposable The correct fix. Object may or may not support IDisposable. object obj Factory.CreateResource using obj as IDisposable Console.WriteLine obj.ToString If obj implements IDisposable the using statement generates the cleanup code. If not the using statement degenerates to using null which is safe but doesn t do anything. If you re not sure whether you should wrap an object in a using block err on the side of safety Assume that it does and wrap it in the using clause shown earlier. That covers the simple case Whenever you use one disposable object that is local to a method wrap that one object in a using statement. Now you can look at a few more complicated usages. Two different objects need to be disposed in that first example the connection and the command. My example creates two different using statements one wrapping each of the two objects that need to be disposed. Each using statement gener- From the Library of Wow eBook Item 15 Utilize using and try finally for Resource Cleanup I 91 ates a different try finally block. In effect you have written this construct public void ExecuteCommand string connString string commandString SqlConnection myConnection null SqlCommand mySqlCommand null try myConnection new SqlConnection connString try mySqlCommand new .