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

Untitled

By: a guest on May 4th, 2012  |  syntax: None  |  size: 2.03 KB  |  hits: 12  |  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. C# how to trigger a callback?
  2. butOK_Click()  //when click the button, disable it
  3. test()  //a wrapper function calling updateUI function
  4. updateUI() // a long process function
  5. callback() // a callback function enabling the button back
  6.        
  7. public delegate void updateUIDelegate(bool refresh);
  8. public delegate void asyncCallback();            
  9. //...
  10. void butOK_Click(object sender, EventArgs e) {
  11.     butOK.Enabled = false;
  12.     test();
  13. }
  14. public void updateUI() {
  15.     // long function....doing 10s
  16. }
  17. public void callback() {
  18.     butOK.Enabled = true;
  19. }
  20. public void test() {
  21.     updateUIDelegate del = new updateUIDelegate(updateUI);
  22.     del.BeginInvoke(null,null);
  23.     //??????????
  24. }
  25.        
  26. void button1_Click(object sender, EventArgs e) {
  27.     button1.Enabled = false;
  28.     BeginAsyncOperation(updateUI);
  29. }
  30. void BeginAsyncOperation(Action operation) {
  31.     operation.BeginInvoke(OnAsyncCallback, null);
  32. }
  33. void OnAsyncCallback(IAsyncResult result) {
  34.     if(result.IsCompleted) {
  35.         if(!InvokeRequired)
  36.             callback();
  37.         else BeginInvoke(new Action(callback));
  38.     }
  39. }
  40. //
  41. public void callback() {
  42.     button1.Enabled = true;
  43.     // something else
  44. }
  45. public void updateUI() {
  46.     // long function....doing 10s
  47.     System.Threading.Thread.Sleep(10000);
  48. }
  49.        
  50. class MyClass {
  51.  
  52.     public delegate void updateUIDelegate(bool refresh);
  53.     public delegate void asyncCallback();            
  54.  
  55.     private void butOK_Click(object sender, EventArgs e)
  56.     {
  57.         butOK.Enabled = false;
  58.         test(new asyncCallback(callback));
  59.     }
  60.  
  61.     public void updateUI(bool refresh)
  62.     {
  63.         // long function....doing 10s
  64.     }
  65.  
  66.     public void callback()
  67.     {
  68.         butOK.Enabled = true;
  69.     }
  70.  
  71.     public void test(asyncCallback callbackMethod)
  72.     {
  73.         updateUIDelegate del = new updateUIDelegate(updateUI);
  74.         del.BeginInvoke(true, null, null);
  75.  
  76.         if(callbackMethod != null) callback();
  77.     }
  78. }
  79.        
  80. updateUIDelegate del = new updateUIDelegate(updateUI);
  81.        
  82. var del = new Action(() => { updateUI(); callback(); });
  83.        
  84. BeginInvoke(callback, null);