0
我需要从不同的url下载几个文本,然后我使用CountDownEvent来处理我的事件Donwnload完成的次数,但事情是我的CountDownEvent永远不会设置为零这仍然在等待。CountdownEvent从不设置为零
任何想法这段代码有什么问题?
namespace WebApplication.AsyncCall
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
private CountdownEvent countDown = null;
public CountdownEvent CountDown
{
get
{
if (this.countDown == null)
{
this.countDown = new CountdownEvent(1);
}
return this.countDown;
}
}
private List<string> text = null;
public List<string> Text
{
get
{
if (this.text == null)
{
this.text = new List<string>();
}
return this.text;
}
}
protected void Page_Load(object sender, EventArgs e)
{
List<string> rssSources = new List<string>();
rssSources.Add(@"http://news.yahoo.com/rss/entertainment");
rssSources.Add(@"http://go.microsoft.com/fwlink/?linkid=84795&clcid=409");
foreach (string uri in rssSources)
{
this.CountDown.AddCount();
LoadSources(uri);
}
this.CountDown.Signal();
this.CountDown.Wait();
}
private void LoadSources(string uri)
{
WebClient client = new WebClient();
client.DownloadStringAsync(new Uri(uri, UriKind.Absolute));
client.DownloadStringCompleted += (s, a) =>
{
if (a.Error == null && !a.Cancelled)
{
this.Text.Add(a.Result);
this.CountDown.Signal();
}
};
}
}
}
在添加侦听器之前完成异步调用吗?尝试移动'client.DownloadStringAsync(new Uri(uri,UriKind.Absolute));'到'LoadSources'方法的末尾,看看它是否有效。 – Jeff
谢谢,但没有工作! –
确定调用回调吗?编辑:另外,你可以尝试在while循环中查询'CountDown'的值,而不是使用'this.CountDown.Wait();'以帮助调试。 – Jeff