简体   繁体   中英

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. 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 . In the Dispose() method, signal the manager that you're no longer in use. 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.

Look into the using statement.

MSDN

Implement the IDisposable interface, and use the keyword 关键字

class MyClass : IDisposable
{
    void Dispose()
    {}
}

using(MyClass obj = Man.GetObj())
{
    obj.DoSomething();
}// obj.Dispose() will be called when the object goes out of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM