Should a class with a Thread element implement IDisposable?

Let's say I have this class Loggerthat writes strings to a low priority workflow that is not a background thread. Lines are queued Logger.WriteLineand flushed to Logger.Worker. No queues in the queue can be lost. Something like this (implementation, locking, synchronization, etc. Omitted for clarity):

public class Logger
{
    private Thread workerThread;
    private Queue<String> logTexts;
    private AutoResetEvent logEvent;
    private AutoResetEvent stopEvent;

    // Locks the queue, adds the text to it and sets the log event.
    public void WriteLine(String text);

    // Sets the stop event without waiting for the thread to stop.
    public void AsyncStop();

    // Waits for any of the log event or stop event to be signalled.
    // If log event is set, it locks the queue, grabs the texts and logs them.
    // If stop event is set, it exits the function and the thread.
    private void Worker();
}

Since the worker thread is the front thread, I should be able to deterministically stop it if the process should be able to complete.

Question: Is the general recommendation in this scenario to allow workflow to be Loggerimplemented IDisposableand stopped in Dispose()? Something like that:

public class Logger : IDisposable
{
    ...

    public void Dispose()
    {
        AsyncStop();
        this.workerThread.Join();
    }
}

?

+3
4

, , - a Thread .. IDisposable using, , - ..

void Foo() {
    ...
    using(var obj = YourObject()) {
        ... some loop?
    }
    ...
}

(, ), ; IDisposable , . , , , , - , .

+3

, ( , /, ..).

+1

, WeakReference , . , ( , , Dispose, Thread.Join), .

+1

, Dispose ( ), , Thread Logger. , supercat, .

+1

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


All Articles