我对一个形成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 */ }
我尝试了类似于上述代码的代码结构,但是正如我所说的,第二个函数在第一个函数运行时没有运行。如果结构错误,有人可以告诉我如何完成这项工作。
预先感谢
Onur
答案 0 :(得分:0)
您可以尝试实现例程的 async 版本,例如
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();
}