Search code examples
multithreadingcommunicationwindowsformsintegration

Multithreaded Library using Worker Thread cannot communicate with UI Thread


I'm using a 3rd party Library to communicate data from a 3rd party input device to a Windows Form. What I am looking to do is gather input data from the device, process it and given certain conditions report back to the Windows UI thread what is going on. I do not have access to the source code of the 3rd party DLL but I do know that the main method is on a background process and I cannot communicate my findings back to the main UI thread I think because I didn't create it?

Windows Form:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // create instance of my listener
        MyListener listener = new MyListener(this);
        Controller controller = new Controller(listener);
   }
}

MyListener Class which extends the 3rd party class Listener:

public class MyListener : Listener
{
    public Form1 form;
    private Frame frame;

    // overloaded constructor
    public LeapListener(Form1 f)
    {
        form = f;
    }

    /// <summary>
    /// onFrame is the main method that runs every milisecond to gather relevant information 
    /// </summary>
    public override void onFrame(Controller controller)
    {
        // Get the most recent frame and report some basic information
        frame = controller.frame();
     }
 }

The issue is that I can communicate back to the main UI thread from anywhere within MyListener class but I cannot communicate back from the onFrame method because it is running on a background thread. Is there anyway to get a hold of the main thread from a background thread I did not create?

I've tried ReportProgress, I've attempted to create an event on MyListener and all attempts to talk to the main UI thread from onFrame crash the application and give me invalid memory location errors.

Any help would be greatly appreciated.


Solution

  • Usually, trying to access a UI object from a thread other than the one handling the UI is problematic. This is not a windows only problem, but a more general pattern.

    The usual solution is to setup some form of event propagation mechanism, which would contain the data needed to update the UI, and let the main thread handle that task.

    Let's call the UI thread UI, and the Background thread BT.

    You could have a function which post an event to UI from BT, and then block BT until the event is processed by UI. It's a simple system using a semaphore to block BT until UI releases it. The advantage of such a system is that it's simple, you don't need to handle more than one event at a time from either thread. The downside is that if events take a long time to be processed, the application would have a very poor sampling resolution from the device. An alternative (and better) way is to create an event queue, have BT post to it, and UI poll it to update itself. It requires a bit more work, but it's way more resilient to UI long timing.

    For that second technique, you must establish a format for your event, setup a shared and mutex guarded queue between BT and UI, and the rest should be easy to do.

    The queue could be something like the following:

    #include <queue>
    
    
    template <typename EVENT>
    class EventQueue {
       protected:
         typedef EventQueue<EVENT> self_type;
         typedef std::queue<EVENT> queue_type;
         Mutex m_;
         queue_type q_;
         void lock(){
             // lock the mutex
         }
         void unlock(){
             // unlock the mutex
         } 
       public:
         EventQueue() {
            // initialize mutex
         }
         ~EventQueue() {
            // destroy mutex
         }
    
         void push(EVENT &e){
             lock();
             q_.push(e);
             unlock();
         }
         EVENT &pop(){
             EVENT &e;
             lock();
             e = q_.pop();
             unlock();
             return e;
         }
         int size(){
             int i;
             lock();
             i = q_.size();
             unlock();
             return i;
         }
    };
    

    This is very simple as you can see, you just have to use the template above with whatever EVENT class you need.

    I have left out the code handling the mutex, it depends on which api you want to depend on. As stated above, UI must only poll the queue, that is check the size of the queue, and take an event out if there's one available. On BT side, all you need to do is to include the event push call in your MyListener class, instead of accessing the form directly.

    This method is very effective at letting both threads working together without stepping on each other toes.