我想从两个不同的网站获取两种类型的数据,并将其绑定到一个列表,但我与异步的问题,我想要做的是从一个rss将它添加到列表中,然后从另一个网站获取信息将其添加到列表中,然后将这两个添加到绑定的可观察集合中。但DownloadStringAsync已经过时运行了,并且应用程序崩溃了。你能帮我吗?我怎样才能做一个异步任务同步
我的代码是所有我相信lamdba会比你的情况的回调更好的
private static ObservableCollection<Top> top= new ObservableCollection<Top>();
private static ObservableCollection<string> place= new ObservableCollection<string>();
// Constructor
public MainPage()
{
InitializeComponent();
if (NetworkInterface.GetIsNetworkAvailable())
{
LoadSiteContent_A(url1);
LoadSiteContent_B(url2);
}
else
MessageBox.Show("No Internet Connection, please connect to use this applacation");
listBox.ItemsSource = top; //trying to bind listbox after web calls
}
public void LoadSiteContent_A(string url)
{
//create a new WebClient object
WebClient clientC = new WebClient();
clientC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(a_DownloadStringCompleted);
clientC.DownloadStringAsync(new Uri(url));
}
public void LoadSiteContent_B(string url)
{
//create a new WebClient object
WebClient clientC = new WebClient();
clientC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(b_DownloadStringCompleted);
clientC.DownloadStringAsync(new Uri(url));
}
public void a_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
string testString = "";
if (!e.Cancelled && e.Error == null)
{
string str;
str = (string)e.Result;
//Various operations and parsing
place.Add(testString);
}
}
}
public void b_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
string testMatch = "";
if (!e.Cancelled && e.Error == null)
{
string str;
// Size the control to fill the form with a margin
str = (string)e.Result;
//Various operations and parsing
top.Add(new Top(testMatch,(place.Count+1)));
}
}
public class TopUsers
{
public string TopUsername { get; set; }
public int Place { get; set; }
public TopUsers(string topusername, int place)
{
this.TopUsername = topusername;
this.Place = place;
}
}
}
如果你希望它是同步的,为什么不直接叫LoadSiteContent_B在a_DownloadStringCompleted()?这将模仿同步活动,但具有异步的好处。 – Archer 2012-04-19 14:48:42
你在异步实现方面做得很好。你只需要找到一种同步添加到可观察集合的方法。提示:查找“锁定”关键字 – Polity 2012-04-19 14:51:53
划伤我的提示,您使用的是静态实例,因此应该重新考虑您的设计。添加到可观察集合应该在主线程上完成。新提示:查找同步。 – Polity 2012-04-19 14:53:53