【发布时间】: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