1

This may well be a dumb question and if this has already been answered elsewhere then I'd really appreciate it if someone could point me to it as my searching hasn't turned up anything definitive.


In a nutshell, my problem is that when I do childThread.Join() in the UI thread on a child thread which has been flagged to stop the childThread seems to block as well as the main thread so everything just hangs.
That the UI will block due to using Join is not a problem in and of itself at the moment since the childThread should finish in under a second after it's told to quit anyway.
This happens while I'm waiting for a thread running a repeating process to quit before I can run another method which returns some information but can't be run at the same time as the other process.

My Winforms application is integrating with a piece of usb hardware by pinvoking the C API for the hardware.

The hardware API has a method that will start off a process that will run indefinitely and repeatedly and rapidly callback with new information which I then need to pass to the UI.
This operation can be cancelled by another call to the hardware API which sets a flag the hardware can see so it knows to quit.
I've wrapped this C API with my own C# code, and within the wrapper I've had to spin out the start process call in another thread so that the activity doesn't block the UI.

Here are the edited highlights of roughly what I'm doing.

public class DeviceWrapper
{
    Thread childThread = null;

    void DeviceWrapper 
    {
        //Set the callback to be used by the StartGettingInformation() process
        PInvokeMethods.SetGetInformationCallback(InformationAcquiredCallback);
    }

    public void StartProcess()
    {
        childThread = new Thread(new ThreadStart(GetInformationProcess))
        childThread.Start();
    }

    void GetInformationProcess()
    {
        PInvokeMethods.StartGettingInformation();
    }

    //This callback occurs inside the childThread
    void InformationAcquiredCallback(Status status, IntPtr information)
    {
        //This callback is triggered when anything happens in the 
        //StartGettingInformation() method, such as when the information 
        //is ready to be retrieved, or when the process has been cancelled.
        if(status == Status.InformationAcquired)
        {
            FireUpdateUIEvent();
        }
        //If the cancel flag has been set to true this will be hit.
        else if(status == Status.Cancelled) 
        {
            //Reset the cancel flag so the next operation works ok
            PInvokeMethods.SetCancelFlag(false); 

            childThread.Abort();
        }
    }

    //This method runs once, and can't run at the same time as GetInformationProcess
    public string GetSpecificInformation()
    {
        //This triggers InformationAcquiredCallback with a status of Cancelled
        StopProcess(); 

        if(childThread.IsAlive)
        {
            childThread.Join();
        }

        return PInvokeMethods.GetSpecificInformation();
    }

    public void StopProcess()
    {
        PInvokeMethods.SetCancelFlag(true);
    }
}

Using this code when I call childThread.Join() the whole application grinds to a halt (which I'd expect for the UI and that's fine) and the childThread also seems to halt because the callback never gets hit again.

However, if I use the following code instead:

public string GetSpecificInformation()
{
    //This triggers InformationAcquiredCallback with a status of Cancelled
    StopProcess(); 
    string s = "";

    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
    {
        if(childThread.IsAlive)
        {
            childThread.Join();
        }
        s = PInvokeMethods.GetSpecificInformation();            
    }));

    return s;
}

Then everything gets hit as expected and childThread does finish and all is well, except obviously my string gets returned empty before the WaitCallback fires and assigns to it.

So, do I just have to suck it up and change the class so that I use the QueueUserWorkItem and WaitCallback and fire an event to deal with my string return?
Is there something daft I'm doing in my first approach that's causing the childThread to block as well?
Or is there another tactic or class entirely that I should be using, bearing in mind it's .NET 3.5 I'm on?

3
  • 3
    I've spent the last 30 years trying to stop Delphi developers using TThread.WaitFor() and other such hard-lock synchronization mechanisms that generate deadlocks. Just when I think I'm getting somewhere, Java and C# developers discover join(). A never-ending nightmare. Apr 3, 2012 at 16:06
  • Believe me I wouldn't be touching any of this unless I was desperate and out of my depth ;) So what would you recommend instead?
    – Nanhydrin
    Apr 3, 2012 at 16:12
  • If you listen to Eric and others re. Invoke, BeginInvoke etc. you will not go far wrong. Don't wait in event-handlers - act on signals returned by having delegates fired on the main thread when the other threads have something to say. Apr 3, 2012 at 17:16

1 Answer 1

5

Well, FireUpdateUIEvent(); sounds like a method that might Post Send to the MsgQueue (Control.Invoke()). When the main thread is waiting in a Join() then you have a classic deadlock.

In Addition, childThread.Abort() is not considered safe.

So, do I just have to suck it up and change the class so that I use the QueueUserWorkItem and WaitCallback and fire an event to deal with my string return?

I certainly would re-design it. It probably can be simplified a bit.

5
  • FireUpdateUIEvent doesn't directly update the UI itself but a handler would certainly be provided for it by the UI alright, and that callback will block waiting for it to return. But since it doesn't actually return a value or anything I care about, I could presumably spin it out into another thread, or is there something better I should be doing?
    – Nanhydrin
    Apr 3, 2012 at 16:09
  • FireUpdateUIEvent should use Control.BeginInvoke, not Control.Invoke. That might solve the deadlock. But you would still have the Join() and the Abort(), not a good situation. Apr 3, 2012 at 16:12
  • @Nanhydrin: Henk is right; you should redesign the whole thing. You should not being doing either a thread abort or a join from the UI thread. If you want to tell the UI thread that something interesting happened on another thread, do the same thing that the operating system does: put a message in its queue. Apr 3, 2012 at 16:12
  • @henk: Aborting a thread is unsafe in a couple of senses: first, you have no guarantee that the thread actually ever will abort; if it is wedged itself into a finally block or some unmanaged code, it will not respond to the abort request. Second, if it does abort you have no idea if it did so in the middle of a critical edit to shared memory, or if it left important resources in half-allocated states. In both those senses it is dangerous. However, it will not corrupt the state of the CLR itself, so it is in that sense "safe". Apr 3, 2012 at 16:14
  • 1
    @Henk: I've confirmed that you were in fact completely right, it was the FireUpdateUIEvent bit that was causing the deadlock. I've change that slightly to use BeginInvoke/EndInvoke on the handlers so that's at least allowed me to prove that the thing can work. Now I just have to go back and ditch the wait. Thank you for your help.
    – Nanhydrin
    Apr 4, 2012 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.