Note that there are some explanatory texts on larger screens.

plurals
  1. POProperly disposing of class with thread
    primarykey
    data
    text
    <p>I have a fairly complex multi-threaded Windows service working, but I can't figure out how to clean up correctly. Below is some [pseudo] code to show what I have. The actual code is much more complex, probably too much to copy/paste here.</p> <p>Basically, I have a class Request that creates a thread to do the work. When a new request comes in the Listener, it sends it to the Processor, which creates the new Request and maintains the list of requests. If the service is stopped, I cleanup all the requests in the list. But when the Request work is done, how do I clean up that one instance of the class?</p> <p>Thanks for any help!</p> <p>Nelson</p> <pre><code>class Service { Listener listener; Processor processor; OnStart() { processor = new Processor(); listener = new Listener(processor); } OnStop() { listener.Dispose(); processor.Dispose(); } } class Listener { Thread thread; bool terminate = false; Listener(Processor processor) { thread = new Thread(DoWork); thread.Start(processor); } DoWork(Processor processor) { WaitForConnection(NewConnection); } NewConnection(String data) { processor.NewRequest(data); if (terminate) return; WaitForConnection(NewConnection); } Dispose() { terminate = true; thread.Join(); } } class Processor { //I need to maintain this list so that when the service stops I can cleanly close down List&lt;Request&gt; requests = new List&lt;Request&gt;(); NewRequest(string data) { request.Add(new Request(data)); } Dispose() { //Cleanup each request foreach (Request request in requests) { request.Dispose(); } } } class Request { Thread thread; bool terminate; Request(string data) { while (true) { //Do some work Thread.Sleep(1000); if (doneWorking) break; if (terminate) return; } //We're done. If I return this thread stops. But how do I properly remove this Request instance from the Processor.requests list? } Dispose() { terminate = true; thread.Join(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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