我编写了一个Eventhandler(异步调用),我通过它下载任何网页的源字符串(HTML),我通过文本框输入URL并将其传递给调用eventhandler的方法,这样可以正常工作,除非是:
我打开应用程序,什么也不做,按“开始”按钮,打开浏览器,将任何链接复制到某个页面,再次按下“开始”按钮。运行应用程序,然后当我将该链接粘贴到文本框并尝试抓取它时,它在无限循环中卡住我的进度指示器,我尝试刷新页面但它没有帮助,这里是下面的代码: / p>
public void LoadSiteContent(string url)
{
//create a new WebClient object
var indicator = new ProgressIndicator
{
IsVisible = true,
IsIndeterminate = true,
Text = "Downloading Source..."
};
try
{
SystemTray.SetProgressIndicator(this, indicator);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback2);
client.DownloadStringAsync(new Uri(url));
}
catch (Exception ex)
{
if (ex is TimeoutException || ex is WebException)
{
MessageBox.Show("It seems there is no response from the remote server (are you connected to the internet?)");
}
}
}
private void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
//Do whatever with the downloaded string (e.Result)
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string Entered_URL = "";
Entered_URL = Enter_URL_Text.Text; //Stored from the textbox
LoadSiteContent(Entered_URL);
}
我如何解决这个问题?谢谢!
答案 0 :(得分:0)
我已经尝试过你的代码了,它运行得很好。由于ProgressIndicator
,我认为它“似乎”陷入了无限循环。您需要在IsIndeterminate
方法中更改Text
和DownloadStringCallback2
属性。
尝试将以下代码添加到DownloadStringCallback2
方法中:
private void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
var indicator = SystemTray.GetProgressIndicator(this);
indicator.IsIndeterminate = false;
indicator.Text = "";
if (!e.Cancelled && e.Error == null)
{
MessageBox.Show("Page load complete.");
//Do whatever with the downloaded string (e.Result)
}
}
并查看它是否按预期工作。