Hi, after reading a few articles, I am still not sure I understand Multi-threading to solve my particular problem.
I have a Main form which will start a background worker thread(worker). The worker thread will doing a While(!Stopping) infinity loop and will sleep at end of each iteration terminate by global Stopping object(Read only lock object). With working fine when user press Stop button, the worker will stop after current iteration.
Now I want when user close the main form, it will set Stop flag first, let the worker thread finish its current job. After that the main form will close. Seems simple enough, but I couldn't make it working.
I tried either worker.Join(), or test woker.IsAlive in a while loop, but both case will lock the application(Main form) after a few seconds for some reason ?
The following is my code inside Form_Closing event handler (not working):
// Tell the thread to stop the file
Stop();
Logger.Info("Stopping the thread by Close the application");
//Not working as well
//worker.Join();
while (worker.IsAlive)
{
Thread.Sleep(5000);
Logger.Info("After sleep for 5 seconds");
}
Logger.Info("worker thread stopped");
One thing interesting is that the worker thread seems always writes log event until the end of each loop iteration, then the rest of the log entry will be main form event inside the while(worker.IsAlive) loop.