0

我有一个包含大约 120,000 个条目的大型数据集,我想逐行解析它。

    private void readDataset()
    {
        totalEntries = File.ReadLines(path).Count();
        entriesRead = 0;
        statusSlider.maxValue = totalEntries;
        statusSlider.minValue = entriesRead;
        statusSlider.value = entriesRead;
        using (StreamReader sr = new StreamReader(path))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                entriesRead++;
                statusSlider.value = entriesRead;
                ...
                ...
            }
        }
    }

不幸的是,使用上面显示的代码,UI 冻结并且仅在解析完成时才开始响应。这意味着,滑块从 0% 跳到 100%,而程序只是在两者之间挂起。

是否可以在不阻塞主 UI 线程的情况下运行它,并且每次 while 循环迭代时也刷新滑块?

4

1 回答 1

0

您可以使用协程。那些不会阻止用户界面。

所以,在你的情况下,你可以这样做;

private void StartReading() 
{
    StartCoroutine(ReadDataSet());
}

private IEnumerator ReadDataSet()
{
    totalEntries = File.ReadLines(path).Count();
    entriesRead = 0;
    statusSlider.maxValue = totalEntries;
    statusSlider.minValue = entriesRead;
    statusSlider.value = entriesRead;
    using (StreamReader sr = new StreamReader(path))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            entriesRead++;
            statusSlider.value = entriesRead;
            ...
            ...
            Debug.Log($"Current Line {entriesRead}, ({(entriesRead/totalEntries)*100f}%)");
            yield return null;
        }
    }
}

阅读每一行后,您将在那里等待一个新帧,它还将打印当前行和总数的百分比。

于 2020-04-29T14:50:19.693 回答