[英]How should i track Objs in use, C#
I have a manager that holds connections to the server. 我有一个与服务器建立连接的管理器。 I keep the connection alive and i want my threads to request connections when it needs. 我保持连接活着,我希望我的线程在需要时请求连接。 My question is 我的问题是
How do i have track objects automatically? 如何自动跟踪对象? I would like it to work similar to scoped pointer. 我希望它的工作方式类似于范围指针。 I request a connection, then when my obj goes out of scope it tells the manager it is not in use anymore. 我请求连接,然后当我的obj超出范围时,它告诉管理器它不再使用了。 I wont be passing it around as a pointer. 我不会将它作为指针传递。 I'll be doing something like 我会做类似的事情
{
Obj = Man.GetObj();
//some loop
Obj.DoSomething()
} //auto tell man that obj is no longer in use
You could create your own wrapper object and implements IDisposable
. 您可以创建自己的包装器对象并实现IDisposable
。 In the Dispose()
method, signal the manager that you're no longer in use. 在Dispose()
方法中,通知管理器您已不再使用。 You can then have your statement like... 然后,您可以将您的陈述视为......
using(Obj obj = Man.GetObj())
{
Obj.DoSomething();
}
The using
block automatically calls the Dispose()
method at the close of the scope. using
块在范围结束时自动调用Dispose()
方法。
Implement the IDisposable interface, and use the using keyword 实现IDisposable接口,并使用using关键字
class MyClass : IDisposable { void Dispose() {} } using(MyClass obj = Man.GetObj()) { obj.DoSomething(); }// obj.Dispose() will be called when the object goes out of scope.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.