Implement System.IDisposable

This topic contains 1 reply, has 1 voice, and was last updated by  Colin 3 weeks, 4 days ago.

  • Author
    Posts
  • #78376

    Colin
    Participant

    Just venturing into creating classes in Powershell and have had a little experience of this in C# as a hobbyist developing the odd work tool.

    I have a class that opens a COM object and I want to make sure that it is properly disposed of in a destructer (which I don't think Powershell classes support?) or implementing iDisposable. Is this possible? I'm having trouble getting it to work.

    Thanks

  • #78491

    Colin
    Participant

    I have now managed to resolve this thankfully. My implementation of IDisposable was correct but I made the wrongful assumption that dispose would get automatically run on all objects at the end of the script by the garbage collector and in a reasonable time. This isn't the case and you need to wrap your code with a using-object block (similar to C#'s USING statement) or manually call the dispose methods. Using-object is better as it runs dispose even after an exception.

    For those that need to achieve the same:

    #Define class inherited from IDisposable
    Class MyClass: System.IDisposable { }
    #Create Dispose Methods
    [void] Dispose()
        { 
            $this.Disposing = $true
            $this.Dispose($true)
            [System.GC]::SuppressFinalize($this)
        }
    
        [void] Dispose([bool]$disposing)
        { 
            if($disposing)
            { 
                #Example of releasing an unmanaged com object
                [System.Runtime.InteropServices.Marshal]::ReleaseComObject($this.myCOMObject)
            }
        }
    #Example using block
    Using-Object ($myInstance = New-Object -TypeName MyClass) { $myInstance.DisplayHelloWorld() }

You must be logged in to reply to this topic.