Note that there are some explanatory texts on larger screens.

plurals
  1. POShould a class with a Thread member implement IDisposable?
    text
    copied!<p>Let's say I have this class <code>Logger</code> that is logging strings in a low-priority worker thread, which <strong>isn't</strong> a background thread. Strings are queued in <code>Logger.WriteLine</code> and munched in <code>Logger.Worker</code>. No queued strings are allowed to be lost. Roughly like this (implementation, locking, synchronizing, etc. omitted for clarity):</p> <pre><code>public class Logger { private Thread workerThread; private Queue&lt;String&gt; 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(); } </code></pre> <p>Since the worker thread is a foreground thread, I have to be able to deterministically stop it if the process should be able to finish.</p> <p><strong>Question:</strong> Is the general recommendation in this scenario to let <code>Logger</code> implement <code>IDisposable</code> and stop the worker thread in <code>Dispose()</code>? Something like this:</p> <pre><code>public class Logger : IDisposable { ... public void Dispose() { AsyncStop(); this.workerThread.Join(); } } </code></pre> <p>Or are there better ways of handling it?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload