In my desktop application am using following .net functions

GC.Collect();
  GC.WaitForPendingFinalizers();

I just want to know that, is there possibility that WaitForPendingFinalizers() will wait for indifinite time ?
If so ,what is the way to get out of it so that my application can proceed further.

Recommended Answers

All 3 Replies

>what is the way to get out of it so that my application can proceed further.

Text from MSDN - http://msdn.microsoft.com/en-us/library/system.gc.waitforpendingfinalizers.aspx

SUMMARY:
The thread on which finalizers are run is unspecified, so there is no guarantee that this method will terminate. However, this thread can be interrupted by another thread while the WaitForPendingFinalizers method is in progress. For example, you can start another thread that waits for a period of time and then interrupts this thread if this thread is still suspended.

You can call something like Release() instead of call GC.WaitForPendingFinalizers() in your main thread

Public Sub Release(Optional ByVal queryDelayInMS As Integer = 100, Optional ByVal waitingCicles As Integer = 10)
        _Wait = True

        Dim gcThread As New Threading.Thread(AddressOf WaitForGC)
        gcThread.Start()

        While _Wait AndAlso waitingCicles > 0
            Threading.Thread.Sleep(queryDelayInMS)
            waitingCicles -= 1
        End While

        If gcThread.IsAlive Then gcThread.Abort()
        _Wait = False

    End Sub

    Private _Wait As Boolean


    Private Sub WaitForGC()
        Try
            GC.Collect()
            GC.WaitForPendingFinalizers()
            Threading.Thread.Sleep(100000)
        Catch
        Finally
            _Wait = False
        End Try
    End Sub

Or better:

Public Sub Realease(Optional ByVal queryDelayInMS As Integer = 100, Optional ByVal waitingCicles As Integer = 10)
        Dim gcThread As New Threading.Thread(AddressOf WaitForGC)
        gcThread.Start()

        While gcThread.IsAlive AndAlso waitingCicles > 0
            Threading.Thread.Sleep(queryDelayInMS)
            waitingCicles -= 1
        End While

        If gcThread.IsAlive Then gcThread.Abort()

    End Sub

    Private _Wait As Boolean


    Private Sub WaitForGC()
        Try
            GC.Collect()
            GC.WaitForPendingFinalizers()
         ---REMOVE THIS LINE It is an example to test   Threading.Thread.Sleep(100000)
        Catch
        End Try
    End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.