我想從兩個不同的網站獲取兩種類型的數據,並將其綁定到一個列表,但我與異步的問題,我想要做的是從一個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