Singleton IDisposable - Good Practice?

I have a Singleton class that controls the connection to an external device. The idea of ​​my application is that I need the external device to be displayed all the time when the application is live.

Singleton has the following features:

  • Initialization, locate the device during application launch
  • interact with an external device, please note that this may apply to multiple assemblies at multiple points.
  • Close the connection when the application terminates.

In the last part, I think about putting the code inside the method Disposefor the singleton class to ensure that the resource will always be cleared when it closes. But since I use Singleton, and since the lifespan of one element will be terminated only after the application exits, there is no need to explicitly close the connection in Dispose, since the connection will still be closed.

So the question is, should I enclose the closed connection code inside the method Dispose?

+3
source share
5 answers

The implementation of IDisposable alone does not mean what Disposeis called upon exit.

, , , , , / Application.Exit( , ).

, , , , , .

Edit:

OPs ( "" ) deconstructor/finalizer. , , ( Dispose):

public class Foo
{
    public Foo()
    {
        //Constructor
    }

    ~Foo()
    {
        // Deconstructor/finalizer
    }
}
+3

IDisposable!= , ++, .

, Singleton , IMO. , - ? , - ? , , .

, Singleton IDisposable.

Singleton .NET. , Application.ApplicationExit( Application.Exit) - .

+2

. Open Close, . , .

+1

, Close() Shutdown(), dispose (track, .., . ...)

, IDisposable ( ) .

Do you use the "final" block around the startup code?

internal static class App
{
    [STAThread]
    private static void Main(string[] args)
    {
        try
        {
            Thing.Startup();
            Application.Run();
        }
        finally
        {
            Thing.Shutdown(); // or dispose
        }
    }
}

Get my drift ?!

PK :-)

PS: "Singleton" should be written as a normal class, the singleton part should be an external practice

0
source

As others have said, Dispose will not be called automatically upon exit, but the finalizer method will be called. I would do this instead of doing your cleanup logic when the application exits.

0
source

Source: https://habr.com/ru/post/1733477/


All Articles