首页 > 解决方案 > 如何在 UI 线程中读取文件

问题描述

我有这样的代码,但是当我运行它时显示“:

不应在 UI 线程上执行同步操作。考虑将此方法包装在 Task.Run 中

我该如何解决这个问题?谢谢

public guchi()
{   
    string[] list = File.ReadAllLines(@"C:\Users\sample.csv");

    foreach (string item in list)
    {
        var tmp = item.Split(';');
        this.Add(new guchi()
        {
           test = tmp[0],
            fun = tmp[1],
            happy = tmp[2],
            run = tmp[3],
            now = tmp[4],
            god = tmp[5],
            time = tmp[6],
            final= tmp[7],
            Pyke = tmp[8],
            Xinzhao = tmp[9]
        });
    }
}

标签: c#uwpreadfile

解决方案


或者使用 API 的异步版本。

File.ReadAllLinesAsync

另外请阅读这篇关于如何在构造函数中使用异步的文章,因为您需要将方法标记为异步才能等待 API 调用。


推荐阅读