文件加载时长挂起时间|二进制|C#|列表



我想知道为什么文件的加载时间这么长。如果你能花点时间看看上面写着的地方,我将不胜感激

if (ReadType == 1)

装载约12000件物品加载一个结构很短的文件需要将近12秒,我认为这是不对的。我是c#的新手,可以使用任何指针。下面是代码和文件结构:这里还附上了这个问题的视频:视频文件的屏幕截图:结构加载

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringEditor
{
public class ItemStr
{
public int a_index;
public byte[] a_name { get; set; }
public byte[] a_descr1 { get; set; }
}
}
private void tsbOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "String|*.lod";
if (ofd.ShowDialog() != DialogResult.OK)
return;
if (!ofd.FileName.Contains("strItem") && !ofd.FileName.Contains("strSkill")) //check to see if user isn't opening the right files if not return;
return;
else if (ofd.FileName.Contains("strItem"))
ReadType = 1;
else if (ofd.FileName.Contains("strSkill"))
ReadType = 2;

FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
if (ReadType == 1)
{
int max = br.ReadInt32();
int max1 = br.ReadInt32();
for (int i = 0; br.BaseStream.Position < br.BaseStream.Length; i++)
{
ItemStr itemstr = new ItemStr();
itemstr.a_index = br.ReadInt32();
itemstr.a_name = br.ReadBytes(br.ReadInt32());
itemstr.a_descr1 = br.ReadBytes(br.ReadInt32());
itemStringList.Add(itemstr);
listBox1.Items.Add(itemstr.a_index.ToString() + " - " + Encoding.GetEncoding(ISO).GetString(itemstr.a_name));

}
EnableFields();

}
fs.Close();
br.Close();
if (ReadType == 2)
{
int max = br.ReadInt32();
int max1 = br.ReadInt32();
for (int i = 0; i < max; i++)
{
skillStr skillStr = new skillStr();
skillStr.a_index = br.ReadInt32();
skillStr.a_name = br.ReadString();
skillStr.a_tool_tip = br.ReadString();
skillStr.a_descr1 = br.ReadString();
skillStringList.Add(skillStr);
string test = skillStr.a_index + "- " + skillStr.a_name;
listBox1.Items.Add(test);

}
EnableFields();

}
fs.Close();
br.Close();
}

我在我的核心i5机器上写了一个小测试。新表单,一个按钮,一个列表框:

private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 30000; i++)
listBox1.Items.Add(i.ToString());
}

(我是根据你截图中的索引号写的(。单击go。在UI再次可用之前,必须等待11秒钟。

我将其修改为:

private void button1_Click(object sender, EventArgs e)
{
listBox1.BeginUpdate();
for (int i = 0; i < 30000; i++)
listBox1.Items.Add(i.ToString());
listBox1.EndUpdate();
}

在它再次可用之前,有一个几乎无法察觉的延迟


大部分问题不是读取文件,而是列表框在逐个添加时刷新了X数千次。使用开始/结束更新来表示您正在加载大量项目。。。

但话说回来,问问自己,一个用户真的会对列表框中的X数万个项目做什么?作为UI/UX指南,避免在列表中加载超过20到30个项目。除此之外,它变得无法航行,尤其是在你装载的数量下。考虑一个要搜索的类型框——滚动条的一个像素跳跃将移动到列表中无法垂直放置的项目中!

如果要将大量数据从文件(或任何位置(加载到列表框中,请考虑使用VirtualList方法-示例如下:

ListView。VirtualMode属性

您可能还想考虑在后台线程中执行加载,这样用户就不会经历加载大量数据可能产生的明显"挂起"延迟。

Listbox.beginupdate((和Listbox.endupdate((解决了我的问题,感谢大家的帮助。

最新更新