2017-06-16 36 views
0

我應該首先聲明,我認爲這個問題的答案是NO,但我想要求確定.....如果您在函數內部打開sqlconnection(使用USING塊),並在到達塊結束之前從該函數返回,那麼該連接是否會被正確處理?在處理sqlconnection之前從函數返回

例如:

Public Function Myfunction() As Boolean 

     Dim ConnectionString As String = "connectionstring goes here" 

     Dim sql As String = "SELECT * FROM mytable" 

     Using connection As New SqlClient.SqlConnection(ConnectionString) 
      Using command As New SqlClient.SqlCommand(sql, connection) 
       connection.Open() 
       Using reader As SqlClient.SqlDataReader = command.ExecuteReader 
        While reader.Read 
          Return True 
        End While 
       End Using 
      End Using 
     End Using 

     Return False 

    End Function 

將上述連接被佈置如果適當地執行返回真實線的?

+3

試試吧,找出來。 – Servy

回答

2

如果你在一個函數內部(用一個USING塊)打開一個sqlconnection,並在到達塊結束之前從該函數返回,那麼這個連接是否會被正確處理?

是的。絕對。這是USING塊的美妙之處。請參閱

一個使用塊的行爲就像一個Try ...最後的構造,其中Try塊使用資源,Finally塊處理它們。正因爲如此,無論您如何退出塊,使用塊都保證資源的處置,。這是真實的,即使在一個未處理的異常的情況下,除StackOverflowException

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/using-statement

相關問題