5

因为我在这里使用“使用”,如果在 TRY 中的任何地方出现异常,FtpWebRequest、FtpWebRespons 和 responseStream 会自动关闭吗?

Try
 Dim request As FtpWebRequest = CType(WebRequest.Create(""), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails

        request.Credentials = New NetworkCredential("", "")
        Using response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)

            Using responseStream As Stream = response.GetResponseStream()
                Using reader As New StreamReader(responseStream)


                    TextBox1.Text = reader.ReadToEnd
                    TextBox1.Text += vbNewLine 
                    TextBox1.Text += vbNewLine
                    ' Use the + for appending (set the textbox to multiline)

                End Using

            End Using

        End Using    

Catch ex As Exception
     MessageBox.Show(ex.Message.ToString())
End Try
4

3 回答 3

8

是的,这三个都将关闭。

Using语句最终Dipose在实现的类上调用方法IDisposable(这发生在Finally编译器生成的部分中)。在这种情况下,这些类将在Dispose被调用时关闭。

很少有例外 - 如果进程退出(例如通过调用语句Environment.ExitUsing),那么Finally块和处置将不会发生。

于 2012-11-02T16:47:21.387 回答
6

Yes they will be disposed of except for when there is a Stack Overflow. From the documentation:

A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException.

于 2012-11-02T16:49:11.827 回答
5

它们将“自动”被处理掉;如果处置关闭了可以打开的东西,那么是的。

于 2012-11-02T16:47:02.663 回答