简体   繁体   English

C#如何用另一个单击事件终止单击事件处理程序

[英]C# How to terminate a click-event handler with another click-event

I have a click-event handler to a button that forms an ssh connection. 我对形成ssh连接的按钮有一个点击事件处理程序。 I want to terminate this function with another "cancel" button click. 我想通过单击另一个“取消”按钮来终止此功能。

However, when executing an event handler, "cancel" click event handler doesn't run while the first handler executing. 但是,在执行事件处理程序时,在第一个处理程序执行时“取消”单击事件处理程序不会运行。 I want to override the first handler with "cancel" handler. 我想用“取消”处理程序覆盖第一个处理程序。

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 */ }

I tried a code-structure like the above code but as I said second function doesnt run while the first function running. 我尝试了类似于上述代码的代码结构,但是正如我所说的那样,第二个函数在第一个函数运行时不会运行。 If the structure is wrong, can someone tell me how to do this job. 如果结构错误,有人可以告诉我如何完成这项工作。

Thanks in advance, 提前致谢,

Onur 奥努尔

You can try implementing async version of your routine, eg 您可以尝试实现例程的异步版本,例如

   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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM