【问题标题】:uwp properties await showing wierd behaviouruwp 属性等待显示奇怪的行为
【发布时间】:2017-06-08 16:40:04
【问题描述】:

在我的 UWP 应用程序中,我有 2 个属性,并且都绑定到 UI。这一切都很好,直到我尝试使用 Task.Delay 延迟添加到这些属性之一。

期望:视频集合属性应该会继续获取项目,不会有任何延迟,而 Current 属性应该会在一些延迟后获取每个项目。

问题:当我尝试延迟两个属性时,两个属性都会延迟,因为在第一次循环运行后延迟实际上会延迟整个循环的执行,但我只想延迟一行代码。

这是我的代码

foreach (var file in VideoFiles)
{
    var props = await file.Properties.GetVideoPropertiesAsync();
    var dur = props.Duration;
    var myviews = await DbHelper.GetMyViews(file.Path);
    var vv = new Video
    {
    MyVideoFile = file,
    Views = myviews,
    Duration = $"{dur.Hours.ToString()} : {dur.Minutes.ToString()} : {dur.Seconds.ToString()}",
    Display = await FileHelper.GetDisplay(file),
    };
    Videos.Add(vv);// this line should be execute without any delay

    await Task.Delay(3000);//if I comment this delay line of code then both properties keep getting filled without any delay, which is not what I want

    Current = vv; // this line should be executed after delay
}

更新

实际上,“视频”是我在 UI 的 GridView 上显示的视频对象的集合,因此我需要立即添加它们。 但是 Current 是一个绑定到我页面上标题的对象,我需要在每 3 秒后更改一次,每 3 秒后标题应该从下一个 GridView 项目中获取数据并显示它,这就是为什么我只在更新时才需要延迟“当前”属性。

【问题讨论】:

  • 您无法在单个循环中处理此问题。填充集合并使用计时器选择下一项
  • 你能提供一些关于如何使用计时器的代码吗?

标签: c# asynchronous uwp async-await uwp-xaml


【解决方案1】:

然后使用 DispatcherTimer 在 for 循环之外设置 Current 属性。像这样的:

public MainPage()
{
    this.InitializeComponent();

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(3);
    int currentIndex = 0;
    timer.Tick += (s, e) =>
    {
        //this code will run every 3 seconds...
        if (Videos.Count > currentIndex)
        {
            Current = Videos[currentIndex++];
        }
    };
    timer.Start();
}

【讨论】:

  • 你能说明我应该如何在循环上下文中使用这个计时器吗?我的意思是我应该在循环开始之前启动 timer.Start() 函数吗?
  • 是的,它将每 3 秒检查一次视频集合。
猜你喜欢
  • 1970-01-01
  • 2015-10-01
  • 1970-01-01
  • 2017-09-13
  • 2018-07-18
  • 2021-11-14
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多