不是每次都从文件中读取行

本文关键字:文件 读取 | 更新日期: 2023-09-27 18:05:19

我是c#和XAML初学者。

在我的应用程序中,我像这样读取文本列表:

string path = "ms-appx:///" + _index + ".txt";
StorageFile sampleFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
_stopsList = await FileIO.ReadLinesAsync(sampleFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);

我把它设置为combobox2:

comboBox2.ItemsSource = routesList[comboBox.SelectedIndex]._stopsList;

有一次我在调试模式下运行我的应用程序,combobox2被正确地填充了来自文件的行(像这样1,但例如下次当我运行我的应用程序时,combobox2是空的(2),旁边的_stopsList出现Count: 0combobox2中的内容不会每次都出现。

BusRoute类:

class BusRoute
{
    public BusRoute(string name, int index)
    {
        Name = name;
        _index = index;
        GetStopsList();
    }
    public async void GetStopsList()
    {
        string path = "ms-appx:///" + _index + ".txt";
        StorageFile sampleFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
        _stopsList = await FileIO.ReadLinesAsync(sampleFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);
    }
    public string Name
    {
        get { return _routeName; }
        set
        {
            if (value != null)
            {
                _routeName = value;
            }
        }
    }
    public IList<string> _stopsList = new List<string>();
    private string _routeName;
    private int _index;
}

主页:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.DataContext = this;
        this.InitializeComponent();
        routesList.Add(new BusRoute("Laszki – Wysocko - Jarosław", 1));
        routesList.Add(new BusRoute("Tuchla - Bobrówka - Jarosław", 2));
        this.comboBox.ItemsSource = routesList;
        this.comboBox.DisplayMemberPath = "Name";
        this.comboBox.SelectedIndex = 0;
        this.comboBox2.ItemsSource = routesList[comboBox.SelectedIndex]._stopsList;
    }
    List<BusRoute> routesList = new List<BusRoute>();
}

不是每次都从文件中读取行

所以这里的问题是GetStopsList()被标记为运行async。当你在BusRoute构造函数中调用GetStopsList时,代码立即继续,最终到达this.comboBox2.ItemsSource = routesList[comboBox.SelectedIndex]._stopsList;。此时ReadLinesAsync还没有完成(构造函数中的执行没有暂停),所以一个空的数据列表被绑定到comboBox2

当你在调试时,这个工作的原因是,当你添加一个断点并检查代码时,你正在造成一个人为的延迟,这使得ReadLinesAsync有足够的时间完成。

尝试将public async void GetStopsList()更改为public async Task GetStopsList(),这将允许调用者将该函数更改为await。然后需要在绑定数据列表之前调用await GetStopsList();

你不能在构造函数中await,所以你需要从其他地方调用初始化函数。这带来了一个有趣的挑战,因为所有代码都在构造函数中。也许有一个Page事件你可以这样做,例如在LoadInit