[英]C# How to terminate a click-event handler with another click-event
我对形成ssh连接的按钮有一个点击事件处理程序。 我想通过单击另一个“取消”按钮来终止此功能。
但是,在执行事件处理程序时,在第一个处理程序执行时“取消”单击事件处理程序不会运行。 我想用“取消”处理程序覆盖第一个处理程序。
private void button_sshconnection_Click(object sender, EventArgs e)
{ /* some code to create ssh connection */ }
private void button_cancel_Click(object sender, EventArgs e)
{ /* some code to terminate button_sshconnection_Click */ }
我尝试了类似于上述代码的代码结构,但是正如我所说的那样,第二个函数在第一个函数运行时不会运行。 如果结构错误,有人可以告诉我如何完成这项工作。
提前致谢,
奥努尔
您可以尝试实现例程的异步版本,例如
private CancellationTokenSource m_Cancellation;
private async void button_sshconnection_Click(object sender, EventArgs e) {
// if method is executing, do nothing. Alternative: cancel and start again
if (m_Cancellation != null)
return;
try {
using (m_Cancellation = new CancellationTokenSource()) {
var token = m_Cancellation.Token;
await Task.Run(() => {
//TODO: implement your logic here, please, note that cancellation is cooperative
// that's why you should check token.IsCancellationRequested
}, token);
}
}
finally {
m_Cancellation = null;
}
}
private void button_cancel_Click(object sender, EventArgs e) {
// If we can cancel, do it
m_Cancellation?.Cancel();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.