2016-04-22 142 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)上有编译错误; - 无法等待无效 –