当 AppDomain 中的任何托管线程终止时,可以调用任意代码吗?
考虑一个用 C# 编写的类库,它在其某些类上使用线程特定字段。类库需要在线程终止时清理数据。
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
}
}
每当托管线程在当前 AppDomain 内终止时,是否有方法调用 FreeSomeData?由于使用此类库的应用程序的复杂性,在线程结束之前显式调用该方法可能不切实际。由于间接层,启动线程的代码甚至可能不知道该类库的存在。
在本机代码中,我会在 DllMain 中完成此操作 并检查了DLL_THREAD_DETACH
的fdwReason
。
非常感谢。
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 appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SomeData
应该有一个可以清理资源的终结器。如果您需要确定性清理,那么没有一个简单的解决方案。分析 API 可能会被滥用来提供您所需的内容,但让
SomeData
实现IDisposable
并将责任推给客户端会更容易。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
implementIDisposable
and push the responsibility to the client.一种选择是创建一个包装 System.Threading.Thread 类的简约线程类。您可以创建自己的线程对象,而不是创建 System.Threading.Thread 对象,该对象执行完全相同的操作,但在线程完成时调用 FreeSomeData() 。
例如:
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: