- C# how to trigger a callback?
- butOK_Click() //when click the button, disable it
- test() //a wrapper function calling updateUI function
- updateUI() // a long process function
- callback() // a callback function enabling the button back
- public delegate void updateUIDelegate(bool refresh);
- public delegate void asyncCallback();
- //...
- void butOK_Click(object sender, EventArgs e) {
- butOK.Enabled = false;
- test();
- }
- public void updateUI() {
- // long function....doing 10s
- }
- public void callback() {
- butOK.Enabled = true;
- }
- public void test() {
- updateUIDelegate del = new updateUIDelegate(updateUI);
- del.BeginInvoke(null,null);
- //??????????
- }
- void button1_Click(object sender, EventArgs e) {
- button1.Enabled = false;
- BeginAsyncOperation(updateUI);
- }
- void BeginAsyncOperation(Action operation) {
- operation.BeginInvoke(OnAsyncCallback, null);
- }
- void OnAsyncCallback(IAsyncResult result) {
- if(result.IsCompleted) {
- if(!InvokeRequired)
- callback();
- else BeginInvoke(new Action(callback));
- }
- }
- //
- public void callback() {
- button1.Enabled = true;
- // something else
- }
- public void updateUI() {
- // long function....doing 10s
- System.Threading.Thread.Sleep(10000);
- }
- class MyClass {
- public delegate void updateUIDelegate(bool refresh);
- public delegate void asyncCallback();
- private void butOK_Click(object sender, EventArgs e)
- {
- butOK.Enabled = false;
- test(new asyncCallback(callback));
- }
- public void updateUI(bool refresh)
- {
- // long function....doing 10s
- }
- public void callback()
- {
- butOK.Enabled = true;
- }
- public void test(asyncCallback callbackMethod)
- {
- updateUIDelegate del = new updateUIDelegate(updateUI);
- del.BeginInvoke(true, null, null);
- if(callbackMethod != null) callback();
- }
- }
- updateUIDelegate del = new updateUIDelegate(updateUI);
- var del = new Action(() => { updateUI(); callback(); });
- BeginInvoke(callback, null);