【问题标题】:Speeding up Importing speed of txt files in c#加快C#中txt文件的导入速度
【发布时间】:2019-07-20 07:49:01
【问题描述】:

所以我一直在尝试通过使用 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];

【问题讨论】:

  • 什么是listBox1?某种用户界面?它极不可能显示 1000000 行,或者如果可以的话,一个人可以阅读它。仅读取和显示适合 UI 的行。您也许可以使用某种虚拟化,但由于您没有向我们展示 listBox1 是什么,我们无法帮助您做到这一点。
  • 既然这工作得很好,我知道这不是代码。你似乎是说,因为只读取 500 个字符并不需要很长时间,所以读取一些未知的字符,较大的金额也不应该花很长时间(尽管这似乎不是有效的代码行)。文件有多大?它包含多少个单词?每次(完成)尝试需要多长时间?
  • 看来,如果您要读取这么多数据,无论如何都会花费一些时间。我能想到的唯一解决方案是Threading 并将列表拆分为不同的文件,每个Thread 读取不同的文件。我还认为您可以使用While (!words.EndOfStream()) { } 并获得相同的输出?不过,这只会有助于提高可读性
  • @Symon 我会采用 Symon 的方法..
  • 是的,您可以将其保存到内存中的数组中。做到这一点的最佳方式将取决于您的应用程序以及您需要访问它的方式/位置。例如,如果这个表单永远不会关闭,只需在表单级别创建一个数组字段。

标签: c#


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2013-08-29
    相关资源
    最近更新 更多