首页 > 解决方案 > 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 */ }

我尝试了类似上面代码的代码结构,但正如我所说的,第二个函数在第一个函数运行时没有运行。如果结构错误,有人可以告诉我如何完成这项工作。

提前致谢,

奥努尔

标签: c#event-handling

解决方案


您可以尝试实现例程的异步版本,例如

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

推荐阅读