Search code examples
c#winformscompact-frameworkwindows-cethread-synchronization

Thread synchronization in WinCE


I have faced with a problem of threads synchronization. My presenter analyzes some sensors and update UI form. I moved updating code into separate thread. It works fine, but if the user stops presenter when it is updating the view, the software freezes - I found that it happens when view.UpdateUI working (it just set some labels using Invoke). Where my problem is? I use compact framework 3.5 and Windows CE 5

using System.Threading;

class MyPresenter
{
  UserControl view;

  private Thread thread;
  private ManualResetEvent cancelEvent;

  public void Start()
  {
    cancelEvent = new ManualResetEvent(false);
    thread = new Thread(UpdateView) { IsBackground = true };
    thread.Start();
  }

  public void Stop()
  {
    if (thread != null) {
      cancelEvent.Set();
      thread.Join();
      thread = null;
    }
  }

  private void UpdateView()
  {
    while (cancelEvent.WaitOne(1000, false) == false) {
      // analyze something
      view.UpdateUI(...);
    }
  }
}

Solution

  • If your background thread is blocked calling your UI (via Control.Invoke), and then your UI thread is blocked calling your Stop method with its thread.Join() you've got yourself a classic fatal embrace. You should get rid of the Join and instead have the background thread raise one last event / notification when the Stop completes so the UI can deal with that (enable/disable buttons etc).