VB.Net/Development/Garbage Collection — различия между версиями

Материал из VB Эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 16:40, 26 мая 2010

Force a garbage collect

 
Imports System
Imports System.Drawing
Imports System.Data
Imports System.IO
Imports System.Collections
Imports System.Windows.Forms
Imports System.Drawing.Printing
Public Class MainClass
    Shared Sub Main()
      Dim o As MyObject = New MyObject
      
      o = Nothing
      GC.Collect()
    End Sub
End Class

Public Class MyObject
    " Constructor - called when the object is started...
    Public Sub New()
        Console.WriteLine("Object " & GetHashCode() & " created.")
    End Sub
    " Finalize - called when the object is removed from memory...
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
        " tell the user we"ve deleted...
        Console.WriteLine("Object " & GetHashCode() & " finalized.")
    End Sub
End Class


Force Garbage Collection

 
Imports System.IO
Module Module1
    Sub Main()
        Dim c1 As New Contact("Name 1", "111-555-1111", "1@1.ru")
        Dim c2 As New Contact("Name 2", "222-555-1212", "2@2.ru")
        Dim c3 As New Contact("Name 3", "333-555-1212", "3@3.ru")
        
        c1 = Nothing " Discard the object
        GC.Collect()
        Console.WriteLine("Back from first collection")
        c3 = Nothing " Discard the object
        GC.Collect()
        Console.WriteLine("Back from second collection -- Press Enter")
        
    End Sub
End Module
    Class Contact
        Public Name As String
        Public Phone As String
        Public EMail As String
        Sub New(ByVal ContactName As String, ByVal ContactPhone As String, ByVal ContactEmail As String)
            Console.WriteLine("Name: " & ContactName & " Phone " & ContactPhone & " Email " & ContactEmail)
            Name = ContactName
            Phone = ContactPhone
            EMail = ContactEmail
        End Sub
        Protected Overrides Sub Finalize()
            Console.WriteLine("In Finalize for " & Name)
        End Sub
    End Class


Garbage collection started

 
Imports System
Public Class MainClass
    
    Shared Sub Main(ByVal args As String())
        Dim myform As New Form1()
    End Sub
End Class
  
Public Class Form1
    Public Running As Boolean
    Private Class Junk
        Public MyForm As Form1
        Public Sub New(ByVal my_form As Form1)
            MyForm = my_form
        End Sub
        " Garbage collection started.
        Protected Overrides Sub Finalize()
            " Stop making objects.
            MyForm.Running = False
        End Sub
    End Class
    Public Sub New()
        Running = True
        Dim new_obj As Junk
        Dim max_i As Long
        For i As Long = 1 To 100000
            new_obj = New Junk(Me)
            If Not Running Then
                max_i = i
                Exit For
            End If
        Next i
        Console.WriteLine("Allocated " & max_i.ToString & " objects")
    End Sub
End Class


GC Suppress Finalize me

 
Imports System
Imports System.Drawing
Imports System.Data
Imports System.IO
Imports System.Collections
Imports System.Windows.Forms
Imports System.Drawing.Printing
Public Class MainClass
    Shared Sub Main()
        Dim file As New MyFile("c:\FinalizeDemo.txt")
        " now, clear the reference to the object...
        file.Dispose()
        file = Nothing
        " wait for the user to press return...
        Console.WriteLine("Press Return to collect the garbage...")
        " force a collect...
        GC.Collect()
        " wait for the user to quit...
        Console.WriteLine("Press Return to quit...")
    End Sub
End Class

Public Class MyFile
    Implements IDisposable
    Private stream As FileStream
    Private isDisposed As Boolean

    Public Sub New(ByVal filename As String)
        stream = New FileStream("test.txt", FileMode.OpenOrCreate)
        Console.WriteLine("Object " & GetHashCode() & " created.")
        Console.WriteLine("Using file: " & filename)
    End Sub
    Public Sub Dispose() Implements System.IDisposable.Dispose
        If isDisposed = True Then Return
        
        stream.Close()
        stream = Nothing
        isDisposed = True
        GC.SuppressFinalize(Me)
        Console.WriteLine("Object " & GetHashCode() & " disposed.")
    End Sub
    Protected Overrides Sub Finalize()
        Dispose()
        Console.WriteLine("Object " & GetHashCode() & " finalized.")
    End Sub
End Class


Get GC generation

  

Module Module1
    Sub Main()
        Dim myObject As Object = New Object()
        Dim i As Integer
        For i = 0 To 3
            Console.WriteLine(String.Format("Generation = {0}", _
                              GC.GetGeneration(myObject)))
            GC.Collect()
            GC.WaitForPendingFinalizers()
        Next i
        Console.Read()
    End Sub
End Module


Object Generation

 
Imports System
Imports System.Text
Imports System.Text.RegularExpressions

Public Class MainClass
    Shared Sub Main(  )
    Dim myObject As Object = New Object()
    Dim i As Integer
    For i = 0 To 3
      Console.WriteLine(String.Format("Generation = {0}", _
                        GC.GetGeneration(myObject)))
      GC.Collect()
      GC.WaitForPendingFinalizers()
    Next i
    End Sub "Main
   
End Class


Request garbage collection

 
Imports System
Public Class MainClass
    Shared Sub Main(ByVal args As String())
      Console.WriteLine("Students before instantiation: " & Student.Count)
      Dim student1 As Student = New Student("A", "B")
      Dim student2 As Student = New Student("C", "D")
      " output of student2 after instantiation
      Console.WriteLine("Students after instantiation: " & vbCrLf & _
         "via Student.Count: " & Student.Count)
      " display name of first and second student
      Console.WriteLine(vbCrLf & "Students 1: " & _
         student1.FirstName & " " & student1.LastName & _
         vbCrLf & "Student 2: " & student2.FirstName & " " & _
         student2.LastName)
      " mark student1 and student2 for garbage collection
      student1 = Nothing
      student2 = Nothing
      System.GC.Collect() " request garbage collection
      
    End Sub
End Class
" Class Student uses Shared variable.
Class Student
   Inherits Object
   Private mFirstName As String
   Private mLastName As String
   " number of objects in memory
   Private Shared mCount As Integer
   " Student constructor
   Public Sub New(ByVal firstNameValue As String, _
      ByVal lastNameValue As String)
      mFirstName = firstNameValue
      mLastName = lastNameValue
      mCount += 1 " increment shared count of students
      Console.WriteLine _
         ("Student object constructor: " & mFirstName & _
         " " & mLastName)
   End Sub " New
   " finalizer method decrements Shared count of students
   Protected Overrides Sub Finalize()
      mCount -= 1 " decrement mCount, resulting in one fewer object
      Console.WriteLine _
         ("Student object finalizer: " & mFirstName & _
         " " & mLastName & "; count = " & mCount)
   End Sub " Finalize
   " return first name
   Public ReadOnly Property FirstName() As String
      Get
         Return mFirstName
      End Get
   End Property " FirstName
   " return last name
   Public ReadOnly Property LastName() As String
      Get
         Return mLastName
      End Get
   End Property " LastName
   " property Count
   Public Shared ReadOnly Property Count() As Integer
      Get
         Return mCount
      End Get
   End Property " Count
End Class " Student