so my problem is that when i set for my wpf application an endless thread the ui hangs but of course this is not what i expect from a multi-threaded application.
heres my code
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate
{
Dispatcher.Invoke(DispatcherPriority.Normal,
new Action<Polyline>(ChangePoints), polyline);
}));
thread.Start();
}
private void ChangePoints(Polyline p)
{
while (true)
{
Random random = new Random();
p.Points.Clear();
for (int i = 0; i < 500; i += 10)
{
p.Points.Add(new Point(i, random.Next(1, 300)));
}
}
}
}
<Window x:Class="ClientSide.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="500">
<Canvas x:Name="canvas" Background="#00FFFFFF">
<Polyline x:Name="polyline" Stroke="DarkGreen" StrokeThickness="3" />
</Canvas>
</Window>
can you guys tell me whats wrong in here?
You create a new thread, but then immediately use the Dispatcher to marshal the thread’s work onto the UI thread. This will cause it to run completely on the UI thread.
Since you’re performing an infinite loop, this causes it to just lock up the UI thread indefinitely.
To correct, you need to switch your logic around. Don’t marshal the call back onto the UI thread for the entire method, but instead build the points, and marshal only the call where you set
p.Pointswithin the loop. You may also need to create some form of delay in there, as it would be running as fast as possible (given the current code), which will likely make the UI unresponsive.Try something like the following: