【发布时间】:2011-06-30 13:19:57
【问题描述】:
我有一个控制台应用程序,它每 1 秒输出大约 160 行信息。
数据输出是可用于在图表上绘制的点。
在我的 WPF 应用程序中,我已经成功连接了这个,并且正在绘制控制台应用程序输出的数据,但是,在大约 500 个左右的数据点之后,我发现应用程序和 UI 线程锁定显着变慢.
我认为这是由于我正在使用的异步操作:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
_process = new Process();
_process.StartInfo.FileName = "consoleApp.exe";
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.RedirectStandardOutput = true;
_process.StartInfo.CreateNoWindow = true;
_process.EnableRaisingEvents = true;
_process.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
_process.Start();
_process.BeginOutputReadLine();
_watch.Start();
};
worker.RunWorkerAsync();
以及负责解析和绘制数据的处理程序:
private void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
var xGroup = Regex.Match(outLine.Data, "x: ?([-0-9]*)").Groups[1];
int x = int.Parse(xGroup.Value);
var yGroup = Regex.Match(outLine.Data, "y: ?([-0-9]*)").Groups[1];
int y = int.Parse(yGroup.Value);
var zGroup = Regex.Match(outLine.Data, "z: ?([-0-9]*)").Groups[1];
int z = int.Parse(zGroup.Value);
Reading reading = new Reading()
{
Time = _watch.Elapsed.TotalMilliseconds,
X = x,
Y = y,
Z = z
};
Dispatcher.Invoke(new Action(() =>
{
_readings.Enqueue(reading);
_dataPointsCount++;
}), System.Windows.Threading.DispatcherPriority.Normal);
}
}
_readings 是this answer 中定义的自定义ObservableQueue<Queue>。我已经对其进行了修改,以便一次只能有 50 个项目在队列中。因此,如果正在添加新项目并且队列计数 >= 50,则在 Enqueue() 之前调用 Dequeue()。
有什么方法可以提高性能,还是因为控制台应用程序的输出量太大而注定要失败?
【问题讨论】:
-
您是否从主应用程序线程启动了进程?如果是这样,这可以解释 UI 锁定。
-
@Chris - 不,我正在为该过程使用后台工作人员。我用更多代码更新了我的问题。
-
感谢您解决这个问题。至少我们知道去别处看看;)
-
那么假设您一次只绘制 50 个点是否正确?
-
是的,队列是一个可观察的集合,当且仅当当前的点数>= 50 时,它才会在入队之前出队