C# 对WPF控件的线程安全调用
我刚刚用WPF和C编写了我的第一个程序。我的windows只包含一个简单的画布控件:C# 对WPF控件的线程安全调用,c#,wpf,xaml,stackpanel,C#,Wpf,Xaml,Stackpanel,我刚刚用WPF和C编写了我的第一个程序。我的windows只包含一个简单的画布控件: <StackPanel Height="311" HorizontalAlignment="Left" Name="PitchPanel" VerticalAlignment="Top" Width="503" Background="Black" x:FieldModifier="public"></StackPanel> 如您所见,有一个名为GraphicsThread的线程。这将
<StackPanel Height="311" HorizontalAlignment="Left" Name="PitchPanel" VerticalAlignment="Top" Width="503" Background="Black" x:FieldModifier="public"></StackPanel>
如您所见,有一个名为GraphicsThread
的线程。这将以尽可能高的速率重新绘制当前游戏状态,如下所示:
public Game(System.Windows.Window Window, System.Windows.Controls.Canvas Canvas)
{
this.Window = Window;
this.Canvas = Canvas;
this.GraphicsThread = new System.Threading.Thread(Draw);
this.GraphicsThread.SetApartmentState(System.Threading.ApartmentState.STA);
this.GraphicsThread.Priority = System.Threading.ThreadPriority.Highest;
this.GraphicsThread.Start();
//...
}
private void Draw() //and calculate
{
//... (Calculation of player positions occurs here)
for (int i = 0; i < Players.Count; i++)
{
System.Windows.Shapes.Ellipse PlayerEllipse = new System.Windows.Shapes.Ellipse();
//... (Modifying the ellipse)
Window.Dispatcher.Invoke(new Action(
delegate()
{
this.Canvas.Children.Add(PlayerEllipse);
}));
}
}
我认为这与中给出的原则相同
那么为什么这不起作用呢?有人知道如何从另一个线程调用控件吗?您不能在其他线程上创建WPF对象-它也必须在Dispatcher线程上创建 这:
必须进入委托。不能在其他线程上创建WPF对象-它也必须在调度程序线程上创建 这: 必须进入学员中。阅读?另请参阅。阅读?另见。
GameInstance = new TeamBall.Game(this, PitchPanel);
System.Windows.Shapes.Ellipse PlayerEllipse = new System.Windows.Shapes.Ellipse();