0

I have a class like this:

class SomeClass
{
    bool isWork;
    Thread workThread;

    public void Start()
    {
        isWork = true;
        workThread = new Thread(new ThreadStart(DoWork));
        workThread.SetApartmentState(ApartmentState.STA);
        workThread.IsBackground = true;
        workThread.Start();
    }

    public void Stop()
    {
        isWork = false;
        workThread.Join();
    }
}

void DoWork()
{
    while (isWork)
    {
        // do work

        Thread.Sleep(100);
    }
}

When application starting it create instance of SomeClass and call it Start() method. Then I call Stop() method of that instance from UI thread and:

  1. isWork set to "false";
  2. main thread join to workThread;
  3. workThread check isWorked and finishet correctly;
  4. main thread freeze on workThread.Join().

As I understant joined thread should continue executing after workThread is over, but it's not true in my situation.

At moment when main thread call workThread.Join() the workThread is alive and exists in debug thread window. But when application freeze workThread not already exists.

  • I can't reproduce this. Are you sure this is the code you're using? – Yuval Itzchakov Jul 27 '15 at 12:05
  • @YuvalItzchakov, I knot that this code should work, but somehow it is not working as it should. I was hoping someone faced a similar anomaly. –  Jul 27 '15 at 12:41
  • 1
    Although I couldn't reconstruct this, set `isWork` as `volatile`. Your other thread might be reading a stale value. – Yuval Itzchakov Jul 27 '15 at 12:46
  • @YuvalItzchakov, with isWork all fine. workthread check it and ends correct. After that joined should be released, but that is not happening. –  Jul 27 '15 at 12:58
  • If I had to venture a guess, the `Join` is not the problem, but the worker thread is not really dead. To test, give it a name before you start it (`workThread.Name = "MyName"`), and then when you believe it's finished break your debugger, go to the Threads window and see if your thread is still there. It might have something to do with you setting it as an STA thread (afaik it's recommended to only have your main UI thread as STA and marshall all UI operations to that thread, also see here: http://stackoverflow.com/questions/4154429/apartmentstate-for-dummies). – tzachs Jul 27 '15 at 13:47
  • @tzachs, yes, thread still there. Code wrote not I and I don't know why thread marked as STA. Thanks for guess, I'll check it. –  Jul 27 '15 at 15:21

0 Answers0