任务冻结GUI



我有这样的情况:从一个任务中,函数"自动化(("被调用,应该在后台运行,但GUI正在冻结。当我使用Task.Delay时GUI也被冻结;自动化(("函数已经完成了它的工作,但在Automation((函数运行时,GUI不应该冻结。我怎样才能做到这一点?我不明白GUI为什么会冻结。非常感谢。

string pair = "A";
private async Task Start()
{
DateTime dueTime = DateTime.Now.AddMilliseconds(1000);
while (true)
{
if (pair =="A")
{
if (TaskA == null) { A_cancelTokenSource.Dispose(); A_cancelTokenSource = new CancellationTokenSource(); TaskA = TaskPairA(A_cancelTokenSource.Token); }
else { if (TaskA.IsCompleted == true) { TaskA.Dispose(); TaskA = null; A_cancelTokenSource.Dispose(); A_cancelTokenSource = new CancellationTokenSource(); TaskA = TaskPairA(A_cancelTokenSource.Token); } }
}
if (pair =="B")
{
if (TaskB == null) { B_cancelTokenSource.Dispose(); B_cancelTokenSource = new CancellationTokenSource(); TaskB = TaskPairB(B_cancelTokenSource.Token); }
else { if (TaskB.IsCompleted == true) { TaskB.Dispose(); TaskB = null; B_cancelTokenSource.Dispose(); B_cancelTokenSource = new CancellationTokenSource(); TaskB = TaskPairB(B_cancelTokenSource.Token); } }
}
await Task.Delay(500);
if (DateTime.Now >= dueTime) { GetAccountData(); dueTime = DateTime.Now.AddMilliseconds(1000); }
}
}

public async Task TaskPairA(CancellationToken ctA)
{
while (true)
{
// other code.....
while (automationFlag == true) { Task.Delay(300); } // This  alone freeze the user interface
Automation(); // This  alone freeze the user interface

// other code.....   Continue here only after "Automation()" is done
}
}

您忘记在那里添加await关键字。

while (automationFlag == true) { await Task.Delay(300); } 
await Automation(); // I think it is also async Task
while(true) // it makes your GUI freeze

你应该使用另一个线程和Dispatcher不让UI锁定

为了不让CPU达到100%,您也应该在while循环中使用Task.Delay()

Task.Run(async() =>
{
while(true) 
{ 
await Task.Delay(2000);
// it only works in WPF
Application.Current.Dispatcher.Invoke(() =>
{
// Do something on the UI thread.
});
}
}

如果有更多关于Automation();的信息,我会给你更好的答案。

最新更新