2016-04-22 141 views
0

美好的一天。請幫助我請如何停止SendPingAsync方法在這裏,我試過SendAsyncCancel但它只停止一個線程,我需要取消所有乒乓線程。通過按鈕點擊停止Ping.SendAsync WPF

private void refreshbtn_Click(object sender, EventArgs e) 
    { 
     if (tokenSource != null) //check if its even initialized or not 
      tokenSource.Cancel(); 

     lstNetworks.Items.Clear(); 
     string gate_ip = NetworkGateway(); 
     //Extracting and pinging all other ip's. 
     string[] array = gate_ip.Split('.'); 
     for (int i = 1; i <= 255; i++) 
     { 
      string ping_var = array[0] + "." + array[1] + "." + array[2] + "." + i; 

      //time in milliseconds   
      Ping(ping_var, 1, 4000); 
     } 
    } 

    public void Ping(string host, int attempts, int timeout) 
    { 
     tokenSource = new CancellationTokenSource(); 
     Task.Factory.StartNew(() => 
     { 
      try 
       { 
        System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); 
        ping.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback); 
        ping.SendAsync(host, timeout, host); 
       } 
       catch 
       { 
        // Do nothing and let it try again until the attempts are exausted. 
        // Exceptions are thrown for normal ping failurs like address lookup 
        // failed. For this reason we are supressing errors. 
       } 
     }, tokenSource.Token); 
    } 

    private void PingCompletedCallback(object sender, PingCompletedEventArgs e) 
    { 
     // If an error occurred, display the exception to the user. 
     if (e.Reply.Status == IPStatus.Success) 
     { 

      string hostName = GetHostName(e.Reply.Address.ToString()); 
      string macAdress = GetMacAddress(e.Reply.Address.ToString()); 
      if (!Dispatcher.CheckAccess()) 
      { 

       Dispatcher.Invoke(new Action(() => 
       { 
         lstNetworks.Items.Add(new InfoItem() { IP = e.Reply.Address.ToString(), MAC = macAdress, HOST = hostName }); 
        lstNetworks.Items.SortDescriptions.Add(new SortDescription("IP", ListSortDirection.Ascending)); 
       })); 
      } 
     } 
     else { 
      //Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString())) 
     } 
    } 

而且每次我點擊刷新按鈕,我應該開始新的ping操作。在我的情況下,只停止一個ping線程,但其餘的繼續工作。

UPDATE

我試着像你寫的,當我再次按下刷新按鈕,我的應用程序凍結,直到所有的線程將停止(30秒)。但是,當應用程序解凍結果是相同的,我以前SendAsync的所有ping數據包都添加了我第二次發送的新的SensAsync數據包。我不僅需要停止線程,還要停止SendAsync線程。有一種方法SendAsyncCancel,但是如何在取消令牌觸發的同一時間調用它。?

回答

1

您正在創建一個TokenSource的不同實例。相反,只能創建一個,將相同的實例傳遞給所有的Tasks。然後,每個Task將檢查Token是否有取消請求,然後您可以每個都等待,並將Token傳遞到該請求中。

private async void refreshbtn_Click(object sender, EventArgs e) 
{ 
    if (tokenSource != null) //check if its even initialized or not 
     tokenSource.Cancel(); 

    lstNetworks.Items.Clear(); 
    string gate_ip = NetworkGateway(); 
    //Extracting and pinging all other ip's. 

    tokenSource = new CancellationTokenSource(); 

    string[] array = gate_ip.Split('.'); 

    List<Task> tasks = new List<Task>(); 
    for (int i = 1; i <= 255; i++) 
    { 
     string ping_var = array[0] + "." + array[1] + "." + array[2] + "." + i; 

     var task = Task.Factory.StartNew(() => 
     { 
      if (tokenSource.Token.IsCancellationRequested) return; 

      //time in milliseconds   
      Ping(ping_var, 1, 4000, tokenSource.Token); 
     }, tokenSource.Token); 
     tasks.Add(task); 
    } 
    await Task.WhenAll(tasks.ToArray()); 
} 

public void Ping(string host, int attempts, int timeout, CancellationToken cancellationToken) 
{ 
    try 
    { 
     System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); 

     cancellationToken.Register(() => ping.SendAsyncCancel()); 

     ping.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback); 
     ping.SendAsync(host, timeout, host); 
    } 
    catch 
    { 
     // Do nothing and let it try again until the attempts are exausted. 
     // Exceptions are thrown for normal ping failurs like address lookup 
     // failed. For this reason we are supressing errors. 
    } 
} 

更新:

新增異步/等待,因此不會阻塞UI。爲每個Ping註冊取消令牌,以便它可以自行取消。

+0

我嘗試像你寫的,當我再次按下刷新按鈕我的應用程序凍結,直到所有線程停止(30秒)。但是,當應用程序解凍結果是相同的,我以前SendAsync的所有ping數據包都添加了我第二次發送的新的SensAsync數據包。我不僅需要停止線程,還要停止SendAsync線程。有一種方法SendAsyncCancel,但是如何在取消令牌觸發的同一時間調用它。? –

+0

查看更新。我添加了代碼,因此它不會阻塞UI線程,並添加使用SendAsyncCancel –

+0

有一些問題。我添加了你的代碼,但是在await Task.WaitAll(tasks.ToArray(),tokenSource.Token)上有編譯錯誤; - 無法等待無效 –