【问题标题】:WPF UI not updating and not sure why?WPF UI 没有更新,不知道为什么?
【发布时间】:2019-01-05 23:32:45
【问题描述】:

我的应用程序中有一个计时器导致线程锁过多,因此我决定将计时器替换为循环运行的任务。现在,在使用任务时,我的 UI 属性没有正确更新。我认为这是一个线程问题,所以我将 UI 更新移到了任务之外并使用了 await,但 UI 仍然无法正常工作。在调试中,我将代码跟踪到 UI,它位于具有正确数据的主线程上,但 UI 永远不会更新。症状是冻结的 UI 和不断增长的进程​​内存。我不知道如何解决这个问题。也许有人可以帮忙?

 private static void OnStaticPropertyChanged([CallerMemberName] string propertyName = null)
    { StaticPropertyChanged?.Invoke(null, new propertyChangedEventArgs(propertyName));
    }

 private void PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        Dispatcher.BeginInvoke((Action)(() =>
       {
           switch (e.PropertyName)
            {
                case "SiderealTime":
                    TextLst.Content = _util.HoursToHMS(TelescopeHardware.SiderealTime);
                    break;
                case "RightAscension":
                    TextRa.Content = _util.HoursToHMS(TelescopeHardware.RightAscension, "h ", "m ", "s", 3);
                    break;
       }));
    }

 private static async void Main_Mount_Loop()
    {            
        _cts = new CancellationTokenSource();
        var ct = _cts.Token;
        var keepGoing = true;
        while (keepGoing)
        {
            var task = Task.Run(() => 
            {
                ct.ThrowIfCancellationRequested();
                Task.Delay(1000, ct);
                MoveAxes();
                if (ct.IsCancellationRequested)
                       {
                           // Clean up here, then...
                           keepGoing = false;
                       }
            }, ct);
            await task;
            UpdateUi();
        }
    }

【问题讨论】:

  • Task.Delay 返回一个应为awaited 的任务。但事实并非如此,也没有延迟。移除外部任务var task = Task.Run,并等待Task.Delay。应该有一些改进
  • 啊,我现在明白了,谢谢!
  • 您为什么使用从不取消取消令牌的取消令牌源。

标签: c# wpf async-await task


【解决方案1】:

Reactive extensions 似乎是更适合这种用法的库:

Observable
    .Interval(TimeSpan.FromSeconds(1), ThreadPoolScheduler.Instance)
    .Do(_ => MoveAxes())
    .SubscribeOn(DispatcherScheduler.Current)
    .Subscribe(_ => UpdateUi());

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2013-10-21
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多