Compartilhar via


Instrução Using (Visual Basic)

Declares the beginning of a Using block and optionally acquires the system resources that the block controls.

Using { resourcelist | resourceexpression }
    [ statements ]
End Using

Parts

Term

Definition

resourcelist

Required if you do not supply resourceexpression. List of one or more system resources that this Using block controls.

resourceexpression

Required if you do not supply resourcelist. Reference variable or expression referring to a system resource to be controlled by this Using block.

statements

Optional. Block of statements that the Using block runs.

End Using

Required. Terminates the definition of the Using block and disposes of all the resources that it controls.

Each resource in the resourcelist part has the following syntax and parts:

resourcename As New resourcetype [ ( [ arglist ] ) ]

- ou -

resourcename As resourcetype = resourceexpression

resourcelist Parts

Term

Definition

resourcename

Required. Reference variable that refers to a system resource that the Using block controls.

New

Required if the Using statement acquires the resource. If you have already acquired the resource, use the second syntax alternative.

resourcetype

Required. The class of the resource. The class must implement the IDisposable interface.

arglist

Optional. List of arguments you are passing to the constructor to create an instance of resourcetype. See Lista de parâmetros (Visual Basic).

resourceexpression

Required. Variable or expression referring to a system resource satisfying the requirements of resourcetype. If you use the second syntax alternative, you must acquire the resource before passing control to the Using statement.

Comentários

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. No entanto, você ainda pode usar um Using bloco para forçar o descarte de um gerenciado recurso em vez de esperar o coletor de lixo.

A Using bloco tem três partes: aquisição, usoe descarte.

  • Acquisition means creating a variable and initializing it to refer to the system resource. The Using statement can acquire one or more resources, or you can acquire exactly one resource before entering the block and supply it to the Using statement. If you supply resourceexpression, you must acquire the resource before passing control to the Using statement.

  • Usage means accessing the resources and performing actions with them. The statements between Using and End Using represent the usage of the resources.

  • Disposal means calling the Dispose method on the object in resourcename. Isso permite que o objeto integralmente terminar seus recursos. The End Using statement disposes of the resources under the Using block's control.

Behavior

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.

The scope of every resource variable acquired by the Using statement is limited to the Using block.

If you specify more than one system resource in the Using statement, the effect is the same as if you nested Using blocks one within another.

Structured Exception Handling Within a Using Block

If you need to handle an exception that might occur within the Using block, you can add a complete Try...Finally construction to it. If you need to handle the case where the Using statement is not successful in acquiring a resource, you can test to see if resourcename is Nothing.

Structured Exception Handling Instead of a Using Block

If you need finer control over the acquisition of the resources, or you need additional code in the Finally block, you can rewrite the Using block as a Try...Finally construction. The following example shows skeleton Try and Using constructions that are equivalent in the acquisition and disposal of resource.

Using resource As New resourceType 
    ' Insert code to work with resource.
End Using
' THE FOLLOWING TRY CONSTRUCTION IS EQUIVALENT TO THE USING BLOCK
Dim resource As New resourceType
Try 
    ' Insert code to work with resource.
Finally 
    resource.Dispose() 
End Try 
ObservaçãoObservação

The code inside the Using block should not assign the object in resourcename to another variable. When you exit the Using block, the resource is disposed, and the other variable cannot access the resource to which it points.

Exemplo

The following example uses a Using block to acquire a new font. This guarantees that the system calls the Dispose method on the font when your code exits the block.

Public Sub setbigbold(ByVal c As Control)
    Using nf As New System.Drawing.Font("Arial", 12.0F, 
        System.Drawing.FontStyle.Bold)

        c.Font = nf
        c.Text = "This is 12-point Arial bold"
    End Using
End Sub

Consulte também

Tarefas

Como: Descartar um recurso do sistema (Visual Basic)

Referência

IDisposable

Instrução Try...Catch...Finally (Visual Basic)

System.Drawing

Font