Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 5th, 2012  |  syntax: None  |  size: 1.15 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Weird InvokeRequired issue
  2. public partial class TreeViewControl : UserControl
  3.   {  
  4.     object mLock = new object();
  5.     void LockAndInvoke(Control c, Action a)
  6.     {
  7.       lock (mLock)
  8.       {
  9.         if (c.InvokeRequired)
  10.         {
  11.           c.Invoke(a);
  12.         }
  13.         else
  14.         {
  15.           a();
  16.         }
  17.       }
  18.     }
  19.  
  20.     public void DataChanged(object sender, NewDataEventArgs e)
  21.     {
  22.       LockAndInvoke(mTreeView, () =>
  23.         {
  24.           // get the data
  25.           mTreeView.BeginUpdate();
  26.           // perform update
  27.           mTreeView.EndUpdate();
  28.         });
  29.     }    
  30.   }
  31.        
  32. private bool b;
  33. public void EventHandler(object sender, EventArgs e)
  34. {
  35.   while(b) Thread.Sleep(1); // give up time to any other waiting threads
  36.   if(InvokeRequired)
  37.   {
  38.     b = true;
  39.     Invoke((MethodInvoker)(()=>EventHandler(sender, e)), null);
  40.     b = false;
  41.   }
  42. }
  43.        
  44. public void DataChanged(object sender, NewDataEventArgs e)
  45. {
  46.       if(InvokeRequired)
  47.       {
  48.           BeginInvoke((MethodInvoker)(()=>DataChanged(sender, e)), null);
  49.           return;
  50.       }
  51.       // get the data
  52.       mTreeView.BeginUpdate();
  53.       // perform update
  54.       mTreeView.EndUpdate();
  55. }