System.InvalidOperationException 绘制到 HelixViewPort3D 时
System.InvalidOperationException when drawing into HelixViewPort3D
总是当我想从进程中绘制到 ViewPort3D 时,我得到 System.InvalidOperationException
。
我不明白的是什么?
是否有进程无法访问 ui 进程?
我该如何解决这个问题?
private void Pro_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Random r = new Random();
DrawSphere(counter, Colors.Red, (double)r.Next(400) / 100);
counter++;
}
private void DrawSphere(int i, Color color, double radius)
{
SphereVisual3D sphere = new SphereVisual3D();
sphere.Center = new Point3D(i * 5, counter * 5, 0);
sphere.Visible = true;
sphere.Fill = new SolidColorBrush(color);
sphere.Radius = radius;
viewPort.Children.Add(sphere);
}
您需要使用调度程序来检查访问权限。您有 2 个选择:
第一个选项:
private void Pro_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Random r = new Random();
Application.Current.Dispatcher.Invoke(new Action(() => DrawSphere(counter, Colors.Red, (double)r.Next(400) / 100)));
counter++;
}
第二个选项:
private void Pro_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Random r = new Random();
DrawToViewPort(counter, Colors.Red, (double)r.Next(400) / 100);
counter++;
}
private void DrawToViewPort(int i, Color color, double radius)
{
if (viewPort.Dispatcher.CheckAccess())
{
DrawSphere(i, color, radius);
}
else
{
viewPort.Dispatcher.Invoke((Action<int, Color, double>)DrawToViewPort, i, color, radius);
}
}
总是当我想从进程中绘制到 ViewPort3D 时,我得到 System.InvalidOperationException
。
我不明白的是什么?
是否有进程无法访问 ui 进程?
我该如何解决这个问题?
private void Pro_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Random r = new Random();
DrawSphere(counter, Colors.Red, (double)r.Next(400) / 100);
counter++;
}
private void DrawSphere(int i, Color color, double radius)
{
SphereVisual3D sphere = new SphereVisual3D();
sphere.Center = new Point3D(i * 5, counter * 5, 0);
sphere.Visible = true;
sphere.Fill = new SolidColorBrush(color);
sphere.Radius = radius;
viewPort.Children.Add(sphere);
}
您需要使用调度程序来检查访问权限。您有 2 个选择: 第一个选项:
private void Pro_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Random r = new Random();
Application.Current.Dispatcher.Invoke(new Action(() => DrawSphere(counter, Colors.Red, (double)r.Next(400) / 100)));
counter++;
}
第二个选项:
private void Pro_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Random r = new Random();
DrawToViewPort(counter, Colors.Red, (double)r.Next(400) / 100);
counter++;
}
private void DrawToViewPort(int i, Color color, double radius)
{
if (viewPort.Dispatcher.CheckAccess())
{
DrawSphere(i, color, radius);
}
else
{
viewPort.Dispatcher.Invoke((Action<int, Color, double>)DrawToViewPort, i, color, radius);
}
}