[英]Populating a listbox from an aysnc httpwebrequest
我目前正在做一個抓取XML文檔的小項目,通過Linq解析它(選擇某些元素),然后通過異步httpwebrequest將它綁定到列表框。
這是代碼;
void ResponseCallBack(IAsyncResult result)
{
//get to the request object
HttpWebRequest myRequest = result.AsyncState as HttpWebRequest;
try
{
//need error checking
HttpWebResponse response = myRequest.EndGetResponse(result)
as HttpWebResponse;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
String s = sr.ReadToEnd();
XElement xmlSearch = XElement.Parse(s);
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
lstbBouquets.ItemsSource = from Search in xmlSearch.Descendants("e2service")
select new GetBouquets
{
e2servicename = Search.Element("e2servicename").Value
};
});
//System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { Debug.WriteLine(s); });
// Stop progress bar
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { performanceProgressBar.IsIndeterminate = false; });
}
}
catch (WebException webExcp)
{
//Debug only, needs error checking
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { Debug.WriteLine(webExcp.ToString()); });
}
}
我是否正確使用調度程序與UI線程交談以更新列表框? 執行時,列表框什么都沒有,我從VS獲得以下輸出;
mscorlib.dll“UI任務”(托管)中出現“System.MethodAccessException”類型的第一次機會異常:已加載“System.SR.dll”mscorlib.dll中出現“System.IO.FileNotFoundException”類型的第一次機會異常System.Windows.Data錯誤:無法從'DreamboxRemote.Pages.GetBouquets'(類型'DreamboxRemote.Pages.GetBouquets')獲取'e2servicename'值(類型'System.String')。 BindingExpression:Path ='e2servicename'DataItem ='DreamboxRemote.Pages.GetBouquets'(HashCode = 98879357); target元素是'System.Windows.Controls.TextBlock'(Name =''); target屬性為'Text'(類型'System.String').. System.MethodAccessException:嘗試訪問該方法失敗:System.Reflection.RuntimeMethodInfo.InternalInvoke中的DreamboxRemote.Pages.GetBouquets.get_e2servicename()(Object obj,BindingFlags invokeAttr System.Reflection.Run的,Binder binder,Object []參數,CultureInfo文化,StackCrawlMark和stackMark)mscorlib.dll中發生了'System.MethodAccessException'類型的第一次機會異常
我認為我沒有正確處理線程,但看不到哪里?
編輯:我應該注意,當取消注釋調試寫入時,它會正確輸出完整的xml文檔。
我懷疑問題是關於linq語句的閉包。
您不能以這種方式綁定ItemsSource。
我將從linq語句中獲取輸出並將其設置為屬性,然后在獲得數據后更新teh UI線程上的實際itemssource。
Bouquets = from Search in xmlSearch.Descendants("e2service")
select new GetBouquets
{
e2servicename = Search.Element("e2servicename").Value
};
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
lstbBouquets.ItemsSource = Bouquets;
});
Search.Element("e2servicename")
可能為null,或
Search.Element("e2servicename").Value
可能會返回null。 顯式轉換運算符(字符串或Nullable)優先於.Value屬性以處理可能的null。
你可以在這里閱讀更多內容。
e2servicename = (string) Search.Element("e2servicename")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.