简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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