Thread synchronization and aborting.

Posted by kubal5003 on Stack Overflow See other posts from Stack Overflow or by kubal5003
Published on 2011-01-17T23:18:32Z Indexed on 2011/01/17 23:53 UTC
Read the original article Hit count: 223

Filed under:
|
|

Hello, I've got a little problem with ending the work of one of my threads. First things first so here's the app "layout":

Thread 1 - worker thread (C++/CLI) - runs and terminates as expected

for(...)
{
  try
  {
    if(TabuStop) return;
    System::Threading::Monitor::Enter("Lock1");
    //some work, unmanaged code
  }
  finally
  {
    if(stop)
    {
      System::Threading::Monitor::Pulse("Lock1");
    }
    else
    {
      System::Threading::Monitor::Pulse("Lock1");
      System::Threading::Monitor::Wait("Lock1");
    }
  }
}

Thread 2 - display results thread (C#)

        while (WorkerThread.IsAlive)
        {
            lock ("Lock1")
            {
                if (TabuEngine.TabuStop)
                {
                    Monitor.Pulse("Lock1");
                }
                else
                {
                    Dispatcher.BeginInvoke(RefreshAction);

                    Monitor.Pulse("Lock1");
                    Monitor.Wait("Lock1", 5000);
                }

            }
           // Thread.Sleep(5000);
        }

I'm trying to shut the whole thing down from app main thread like this:

        TabuEngine.TabuStop = true; //terminates nicely the worker thread and 
        if (DisplayThread.IsAlive)
        {
            DisplayThread.Abort();
        }

I also tried using DisplayThread.Interrupt, but it always blocks on Monitor.Wait("Lock1", 5000); and I can't get rid of it. What is wrong here? How am I supposed to perform the synchronization and let it do the work that it is supposed to do?

//edit I'm not even sure now if the trick with using "Lock1" string is really working and locks are placed on the same object..

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading