I'm writing an application that uses a separate thread for logging. I'd like to stop the separate thread when the main thread stops. However I'm unable to figure out when to stop the logger thread exactly as I don't know when the main thread stops. Is there a mechanism in C# that would send a notification when the main thread stops? (Or can you think about another solution to my problem?)
// This class automatically applies on each call of every method of Main() function
public class CommandLoggingAdvice : IMethodInterceptor
{
private static ProducerConsumerClass LoggingQueue = ProducerConsumerClass.Instance;
LoggingQueue.AddTask("Logging message on call of *method*");
}
public sealed class ProducerConsumerClass
{
// here Iget an instance of log4net
private ILog _Logger = null;
protected ILog Logger
{
_Logger = LogManager.GetLogger("Logger1");
}
private BlockingCollection<string> tasks = new BlockingCollection<string>();
private static volatile ProducerConsumerClass _instance;
Thread worker;
private Thread mainthread;
private ProducerConsumerClass()
{
mainthread = Thread.CurrentThread;
worker = new Thread(Work);
worker.Name = "Queue thread";
worker.IsBackground = false;
worker.Start(mainthread);
}
public static ProducerConsumerClass Instance
{
get
{
if (_instance == null)
{
_instance = new ProducerConsumerClass();
}
}
}
public void AddTask(string task)
{
tasks.Add(task);
}
void Work(object mainthread)
{
Thread ma = (Thread) mainthread;
if(ma.ThreadState != ThreadState.Stopped)
{
tasks.CompleteAdding();
}
while (true)
{
string task = null;
if (!tasks.IsCompleted)
{
task = tasks.Take();
Logger1.Info(task);
}
else
{
return;
}
}
}
}
If BlockingCollection is empty and application is still working, loop calls one more Take() and result: logger thread is paused now. So when main thread.Threadstate == Stopped, i need to kill logger thread
More info about issue were added in comments