在另一个线程中将项添加到DataGrid



我正在尝试使用WPF将项添加到DataGrid中,使UI不会冻结。

背景:我有一个IP地址列表。对于这些IP地址,应该确定进一步的信息,例如ping。这意味着,我遍历IP列表的每一项,根据IP确定数据,并将结果插入到一个新列表中。这个新列表的内容应该显示在DataGrid中。

现在是这样的,大约有4000个IP。据估计,每秒大约有15个条目将被添加到DataGrid列表中。但是,只有在处理了一个列表中的所有项目并将其添加到新列表中后,才会显示该列表。

我的目标是让它看起来像这样:https://www.youtube.com/watch?v=xWC1GvfCI0I

你可能知道如何最好地解决这个问题吗?这是我最后一次尝试的方式:

public void Get()
{
Task.Run(() =>
{
using (var client = new WebClient())
{
var ips = client.DownloadString("http://monitor.sacnr.com/list/masterlist.txt");
using (var reader = new StringReader(ips))
{
for (string ip = reader.ReadLine(); ip != null; ip = reader.ReadLine())
{
this.Servers.Add(this._sacnr.GetServerProperties(ip));
}
}
}
});
}

谢谢。

我现在是这样做的。

我这样称呼我的方法:Task.Factory.StartNew(() => this.Get());

然后我用这样的方法:

public void Get()
{
var sacnr = new SacnrConnector();
using (var client = new WebClient())
{
var ips = client.DownloadString("http://monitor.sacnr.com/list/masterlist.txt");
using (var reader = new StringReader(ips))
{
for (string ip = reader.ReadLine(); ip != null; ip = reader.ReadLine())
{
var server = sacnr.GetServerProperties(ip);
// Here I use BeginInvoke to add elements to my ObservableCollection
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), server);
}
}
}
}
private void AddItem(object server)
{
this.Servers.Add((Server)server);
}

它起作用了!

最新更新