Is it possible to call arbitrary code when any managed thread ends in AppDomain?

Consider a class library written in C # that uses streaming specific fields for some of its classes. The class library should clear the data when the thread terminates.

namespace MySdk
{
  public class MyClass
  {
    [ThreadStatic]
    private static SomeData _data; 

    public static SomeData Data
    {
       get
       {
         if(_data == null)
         {
           _data = new SomeData();
         }
         return _data;
       }
    }

    public static void FreeSomeData()
    {
      // Release _data 
    }

    // some other useful data which uses _data

  }  
} 

Is there a way to call FreeSomeData whenever a managed thread terminates in the current AppDomain? Due to the complexity of applications using this class library, it may not be practical to call the method explicitly before the end of the stream. The code that starts the threads may not even know that this class library exists because of layers of indirection.

In native code, I would do this in DllMain and check fdwReasonfor DLL_THREAD_DETACH.

Great importance.

+3
2

SomeData , .

, . API , , , SomeData IDisposable .

+1

- , System.Threading.Thread. System.Threading.Thread , , FreeSomeData(), .

:

class MyThread
{
    private Action _worker;

    public MyThread(Action worker)
    {
        _worker = worker;
    }

    public void Start()
    {
        var t = new System.Threading.Thread(doWork);
        t.Start();
    }

    private void doWork()
    {
        _worker();
        MyClass.FreeSomeData();
    }
}
0

All Articles