2016-05-24 45 views
0

我做了一個使用WebRequest請求10倍HTTP頭的異步方法。只要網址無效,我的程序工作正常。該URL是否有效,只發送兩個請求。使用HttpWebRequest的死鎖

要檢查這個,我做了兩個按鈕,一個檢查有效的URL,一個檢查無效的URL。如果我使用有效的URL,我的計數器會精確地增加2,但只是第一次。有趣的是,我仍然可以按下無效URL的按鈕並按預期工作。

這是CS文件:

public partial class MainWindow : Window 
{ 
    int counter = 0; 

    private async Task DoWork(String url) 
    { 
     for (int i = 0; i < 10; i++) 
     { 
      HttpWebRequest request = WebRequest.CreateHttp(url); 
      request.Method = "HEAD"; 
      request.Timeout = 100; 

      HttpWebResponse response = null; 

      try 
      { 
       response = (HttpWebResponse)await request.GetResponseAsync(); 
      } 
      catch(Exception ex) 
      { 

      } 

      counter++; 
      Dispatcher.Invoke(() => label.Content = counter); 
     } 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     DoWork("http://www.google.ch"); 
    } 

    private void Button_Click_1(object sender, RoutedEventArgs e) 
    { 
     DoWork("http://www.adhgfqliehfvufdigvhlnqaernglkjhr.ch"); 
    } 
} 

這是XAML文件

<Window x:Class="WpfApplication2.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Label Name="label" Content="Label" HorizontalAlignment="Left" Margin="78,151,0,0" VerticalAlignment="Top"/> 
     <Button Content="Valid URL" HorizontalAlignment="Left" Margin="64,71,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/> 
     <Button Content="Invalid URL" HorizontalAlignment="Left" Margin="144,71,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/> 
    </Grid> 
</Window> 

有人能解釋這個行爲的研究?

+0

據透露,你不需要Dispatcher.Invoke。這是一個很好的等待。 – usr

回答

0

由於異步方法,問題不像預期的那樣出現死鎖。這是因爲我沒有使用HttpWebResponse的處置。

在這裏,我們找到了一絲解決這個問題 HttpWebResponse get stuck while running in a loop

還解釋是,爲什麼它的工作恰好兩次。連接似乎保持開放,並有一個ConnectionLimit: System.Net.ServicePointManager.DefaultConnectionLimit

添加處置解決了這個問題:

  try 
      { 
       response = (HttpWebResponse)await request.GetResponseAsync(); 
      } 
      catch (Exception ex) 
      { 

      } 
      finally 
      { 
       if (response != null) 
       { 
        response.Dispose(); 
       } 
      } 
+1

當然你也可以用「使用」來解決問題 –