Compartilhar via


Como: Descartar um recurso do sistema (Visual Basic)

You can use a Using block to guarantee that the system disposes of a resource when your code exits the block. This is useful if you are using a system resource that consumes a large amount of memory, or that other components also want to use.

To dispose of a database connection when your code is finished with it

  1. Make sure you include the appropriate Declaração Imports (Tipo e Namespace .NET) for the database connection at the beginning of your source file (in this case, System.Data.SqlClient).

  2. Create a Using block with the Using and End Using statements. Inside the block, put the code that deals with the database connection.

  3. Declare the connection and create an instance of it as part of the Using statement.

    ' Insert the following line at the beginning of your source file.
    Imports System.Data.SqlClient
    Public Sub AccessSql(ByVal s As String)
        Using sqc As New System.Data.SqlClient.SqlConnection(s)
            MsgBox("Connected with string """ & sqc.ConnectionString & """")
        End Using
    End Sub
    

    The system disposes of the resource no matter how you exit the block, including the case of an unhandled exception.

    Note that you cannot access sqc from outside the Using block, because its scope is limited to the block.

    You can use this same technique on a system resource such as a file handle or a COM wrapper. You use a Using block when you want to be sure to leave the resource available for other components after you have exited the Using block.

Consulte também

Tarefas

Como: Transferir controle para fora de uma estrutura de controle (Visual Basic)

Como: Executar várias ações em um objeto (Visual Basic)

Referência

Instrução Using (Visual Basic)

SqlConnection

Conceitos

Estruturas de decisão (Visual Basic)

Estruturas de loop (Visual Basic)

Outras estruturas de controle (Visual Basic)

Estruturas de controle aninhado (Visual Basic)

Outros recursos

Fluxo de controle no Visual Basic