Can one invoke arbitrary code when any managed thread is terminated within an AppDomain?
Consider an class library written in C# which uses thread specific fields on some of its classes. The class library needs to clean up 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 invoke FreeSomeData whenever a managed thread terminates within the current AppDomain? Due to the complexity of the applications that use this class library, it may be impractical to call the method explicitly before a thread ends. The code that starts the threads may not even know this class library exists due to layers of indirection.
In native code, I would have done this in DllMain and checked fdwReason
for the DLL_THREAD_DETACH
.
Much appreciat开发者_StackOverflow社区ed.
SomeData
should have a finalizer that would clean up resources.
If you need deterministic cleanup, then there is not an easy solution. The profiling APIs may be able to be abused to provide what you need, but it would be much easier to have SomeData
implement IDisposable
and push the responsibility to the client.
One option is to create a minimalistic thread class that wraps the System.Threading.Thread class. Instead of creating a System.Threading.Thread object, you can create your own thread object which does exactly the same thing, but calls FreeSomeData() when the thread is finished.
For example:
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();
}
}
精彩评论