c# - C#如何用另一个点击事件终止一个点击事件处理程序
问题描述
我对形成 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();
}
推荐阅读
- swift - Swift:在运行时获取所有活跃的编译条件?
- r - 如何遍历 R 中的列来创建绘图?
- c++ - emplace 方法的模板前缀
- r - ggplot:如何选择高于某个阈值但仍显示正确百分比的数据
- google-app-engine - 谁启动了谷歌云调度程序?
- javascript - 为什么“in”不能用于检查特定单词是否在 JavaScript 的数组中
- reactjs - AWS chime 反应没有音频输入
- css - 边框图像源:线性渐变仅读取一种颜色
- javascript - 在 URL 动态更改上重新运行 Firefox 插件的脚本
- powershell - 将 VBScript 代码转换为 Power Shell 代码以将值写入 Windows 10 工作站的 Active Directory 计算机帐户描述