我做了一個使用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>
有人能解釋這個行爲的研究?
據透露,你不需要Dispatcher.Invoke。這是一個很好的等待。 – usr