我正在构建一个rss提要阅读器。我使用Visual studio创建了一个入门应用程序。在它的主页上,我添加了一个链接到一个新的数据透视页。所有rss的事情都发生在我的数据透视页面上。现在,在我的rss提要列表框中,我最初使用以下代码设置了一些列表项:
public PivotPage1()
{
InitializeComponent();
getMeTheNews();
addToCollection("Android is going up","TechCrunch");
lstBox.DataContext = theCollection;
}
private void addToCollection(string p1, string p2)
{
theCollection.Add(new NewsArticle(p1,p2));
}
以下是另外两个函数,其中rss是从服务器获取并解析的,但当我想在getTheResponse()
方法中向ObservableCollection
添加已处理的条目时,会导致无效的跨线程访问错误。有什么想法吗?
代码:
private void getMeTheNews()
{
String url = "http://rss.cnn.com/rss/edition.rss";
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.BeginGetResponse(getTheResponse, webRequest);
}
private void getTheResponse(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
try
{
WebResponse response = request.EndGetResponse(result);
XDocument doc = XDocument.Load(response.GetResponseStream());
IEnumerable<XElement> articles = doc.Descendants("item");
foreach (var article in articles) {
System.Diagnostics.Debug.WriteLine(article);
try
{
System.Diagnostics.Debug.WriteLine(article.Element("title").Value);
addToCollection(article.Element("title").Value,"CNN");
}
catch (NullReferenceException e) {
System.Diagnostics.Debug.WriteLine(e.StackTrace);
}
}
}
catch(WebException e) {
System.Diagnostics.Debug.WriteLine(e.StackTrace.ToString());
}
}
else
{
}
}
您需要使用Dispatcher
从非UI线程访问Control
:
Deployment.Current.Dispatcher.BeginInvoke(()=>
{
addToCollection(article.Element("title").Value,"CNN");
});
跨线程收集同步
将ListBox绑定到ObservableCollection,当数据发生更改时,您将更新ListBox,因为实现了INotifyCollectionChanged。dell‘ObservableCollection的缺陷在于,数据只能由创建它的线程更改
SynchronizedCollection不存在多线程问题,但不会更新ListBox,因为它没有实现INotifyCollectionChanged,即使实现了INotifyCollectionChanged,CollectionChanged(this,e)也只能从创建它的线程调用。。所以它不起作用。
结论
-如果您想要一个自动更新单线程的列表,请使用ObservableCollection
-如果您想要不自动更新但多线程的列表,请使用SynchronizedCollection
-如果两者都想要,请使用Framework 4.5、BindingOperations.EnableCollectionSynchronization和ObservableCollection(),方法如下:
/ / Creates the lock object somewhere
private static object _lock = new object () ;
...
/ / Enable the cross acces to this collection elsewhere
BindingOperations.EnableCollectionSynchronization ( _persons , _lock )
完整样本http://10rem.net/blog/2012/01/20/wpf-45-cross-thread-collection-synchronization-redux
您可以使用Dispatcher,从ObservableCollection开始,使用OnCollectionChanged 方法
public class MyObservableCollectionOverrideCollChangOfObjects<T> : ObservableCollection<T>
{
...
#region CollectionChanged
public override event NotifyCollectionChangedEventHandler CollectionChanged;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
var eh = CollectionChanged;
if (eh != null)
{
Dispatcher dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()
let dpo = nh.Target as DispatcherObject
where dpo != null
select dpo.Dispatcher).FirstOrDefault();
if (dispatcher != null && dispatcher.CheckAccess() == false)
{
dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => OnCollectionChanged(e)));
}
else
{
foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
nh.Invoke(this, e);
}
}
}
#endregion
..
}