【问题标题】:Lines aren't read from file every time不是每次都从文件中读取行
【发布时间】:2016-09-02 06:16:12
【问题描述】:

我是 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>();
}

【问题讨论】:

  • 这确实按预期工作。因此,要么您有更多代码,要么您正在做的事情超出您所说的范围,或者您的设备上发生了一些奇怪的事情,导致该文件出现问题......
  • 我添加了 BusRoute 类和 MainPage 的代码,大家可以看看。它几乎是完整的代码。
  • 下面已经有人回答了你。这也不是编写应用程序的正确方法,您应该使用绑定。虽然可以像上面那样做一些事情,但它在很多方面已经过时,应该避免。

标签: c# xaml text-files


【解决方案1】:

所以这里的问题是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 上。

【讨论】:

  • 你不能在构造函数中等待(除非他们为 C# 6 改变了它)
  • @ScottChamberlain,啊,没想到!
  • 我将设置 combobox2 源放入页面的 Loaded 事件中。它现在完美运行。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
相关资源
最近更新 更多