gpt4 book ai didi

C#如何触发回调?

转载 作者:行者123 更新时间:2023-11-30 17:14:10 26 4
gpt4 key购买 nike

这是我的代码片段的一部分。我想将回调函数传递给 test()。因此,在调用“del”委托(delegate)后,是否可以自动触发回调()?

函数:

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);
}

另请参阅以下文章:Calling Synchronous Methods Asynchronously

关于C#如何触发回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9028794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com