首页 > 解决方案 > 加快在c#中导入txt文件的速度

问题描述

所以我一直在尝试通过使用 txt 文件将所有英文单词导入我的程序。而且由于有很多英文单词,我在下面底部的当前方法确实需要很长时间。但我也试过:

string a = words.ReadToEnd();

这也没有那么好。我使用以下方法减少了程序必须输入的字数:

string a = words.ReadBlock(char[],0,500);

而且由于这工作得很好,我知道这不是代码。所以我的问题是如何加快这个过程,如果我将字符串保存在“设置”中或者它是否必须加载很长时间,它是否会立即加载。谢谢你的帮助。

    public FrmMain()
    {

        InitializeComponent();
        System.IO.StreamReader words = new System.IO.StreamReader(@"C:\Users\Cyril\Downloads\words_alpha.txt");
        string line;
        int counter = 0;
        while((line=words.ReadLine())!=null)
        {
            listBox1.Items.Add(line);
            dict[counter] = line;
            counter++;
        }
    }
    string[] dict = new string[1000000];

标签: c#

解决方案


我使用控制台应用程序编写和读取数千到百万个随机字符串并得到以下结果:

One Thousand words :: To generate : 8 milliseconds, To read : 9 milliseconds
Ten Thousand words :: To generate : 14 milliseconds, To read : 7 milliseconds
Hundred Thousand words :: To generate : 73 milliseconds, To read : 12 milliseconds
One Million words:: To generate : 525 milliseconds, To read : 181 milliseconds

然后我尝试使用主线程(由 OP 完成)将它们加载到 Win Forms 列表框中,并且由于长时间运行的操作挂起主 UI 线程而超时。

OP 需要使用此 stackoverflow 问题中讨论的虚拟视图: C# Virtual List View in WinForms

此处给出了示例代码(来自上述 SFQ): https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.listview.virtualmode?redirectedfrom=MSDN&view=netframework-4.7。 2#System_Windows_Forms_ListView_VirtualMode


推荐阅读