簡體   English   中英

C#如何用另一個單擊事件終止單擊事件處理程序

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

我對形成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();
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM