ActiveX
ActiveX

Reputation: 1166

IDisposable Pattern - Is Dispose() invoked when an object is stored in a Thread local data?

All,

I have a class FileLogger that implements IDisposable pattern. The instance of this class is stored in current thread's local data:

LocalDataStoreSlot s;
s = Thread.GetNamedDataSlot("logger");

if (Thread.GetData(s) == null)
    Thread.SetData(s, new FileLogger());

Nowhere in the code I call Dispose() on my class but when the process ends, the finalizer is not invoked. Here's the implementation of the IDisposable pattern in my class:

protected virtual void Dispose(bool disposing)
{
    if (!_isDisposed)
    {
        if (disposing)
        {   
        }

            try
            {
                closeFile_();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

        _isDisposed = true;
    }
}

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

~FileLogger()
{
    Dispose(false);
}

closeFile_() method is never invoked (I know it is not being invoked because this method should write into the file some closing html tags). Why?

Upvotes: 1

Views: 221

Answers (1)

ActiveX
ActiveX

Reputation: 1166

As pointed out by Ralf:

NET 5 (including .NET Core) and later versions don't call finalizers as part of application termination.

Source

Upvotes: 1

Related Questions