【发布时间】:2014-04-23 05:52:50
【问题描述】:
我正在做口译员。 UI 是一个 WPF 应用程序。单击按钮后,我启动了一个必须写入 ui 的长任务。过去,我和一名后台工作人员做过类似的事情。我意识到后台工作人员已经过时,异步是要走的路(噪音更小,更干净等)。
我的长期任务是在循环播放时顺利地将文本写入屏幕,但屏幕仍然“冻结”,即无法点击按钮等。
如果我在 task.run 结束时添加 30 毫秒的睡眠,UI 会响应并且我的对象事件正在工作。但是睡眠似乎使它比 30 毫秒慢得多。
private void AnalyzeButton_Click( object sender, RoutedEventArgs e )
{
var flowManager = new InterpreterFlowManager(){ ... }
flowManager.Initialize();
flowManager.ContinueFlow();
}
....
public class InterpreterFlowManager
{
async public void ContinueFlow()
{
string LineBuffer = "";
string lastTextBlockString = "";
while (...)
{
lastTextBlockString = "";
bool endLoop = false;
await Task.Run(() =>
{
if (...)
{
...
if (...)
{
switch (...)
{
case x:
lastTextBlockString = "\r\nEntrer un nombre :";
endLoop = true;
break;
case y:
lastTextBlockString = "\r\n" + ConsoleInfo.Message;
break;
}
}
}
else
LineIndex++;
*********************************
SMALL SLEEP HERE MAKE UI RESPONSIVE.
************************************
});
//ACCESS TO A UI TEXTBOX
var lastTextBlock = (InteractiveWindow.Children.Cast<TextBox>().Where(c => c.GetType() == typeof(TextBox) && c.IsReadOnly)).Last();
//SUCESSFULLY APPEND
lastTextBlock.Text += lastTextBlockString;
Output.Text += _tmpResultString + "\r\n";
_tmpResultString.Clear();
if (endLoop)
{
TextBox input = new TextBox();
input.BorderBrush = Brushes.DarkRed;
input.KeyUp += input_KeyUp; // further stuff
InteractiveWindow.Children.Add(input);
return;
}
}
}
}
【问题讨论】:
标签: c# wpf async-await