Reputation: 18086
My application has work to do in background in another thread and the Gui drawing result from list the background thread fill this list
In initialization I made the background thread and when I press button in Gui this thread begin working ; and I click on another buttom to read result while the background thread working but The GUI is very very slow to response to result.
is there any solution I want my results display on GUI faster ?
my code:
Thread startdrawingthread = new Thread(StartDrawing);
public MainWindow()
{
InitializeComponent();
}
private void bt_draw_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (ch_single.IsChecked == true || ch_entire.IsChecked == true)
{
currentMode = "";
startdrawingthread.Start();
//StartDrawing();
real_area.DrawingArea.Children.Clear();
real_area.DrawGrid(20);
}
}
private void bt_single_next_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (GlobalV.isfinished == false)
{
while (true)
{
if (GlobalV.Attatched_Elements.Count > 0)
{
try
{
real_area.DrawingArea.Children.Clear();
real_area.DrawGrid(20);
real_area.DrawElement(GlobalV.Attatched_Elements[i]);
i++;
}
catch
{
}
break;
}
}
}
}
Upvotes: 2
Views: 1010
Reputation: 128013
The problem is, as long as GlobalV.Attatched_Elements.Count
is zero, your event handler goes through an endless loop of while (true)
.
I guess that GlobalV.Attatched_Elements.Count
is set somewhere in StartDrawing
, but you can not busy-wait like this until it gets greater than zero. You should perhaps remove the whole if (GlobalV.isfinished == false)
and while (true)
blocks and simply do the following, which especially does nothing if there is nothing to do:
private void bt_single_next_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (GlobalV.Attached_Elements.Count > 0)
{
...
}
}
maybe with also locking the collection for thread-safe access:
private void bt_single_next_Click(object sender, System.Windows.RoutedEventArgs e)
{
lock (GlobalV.Attached_Elements)
{
if (GlobalV.Attached_Elements.Count > 0)
{
...
}
}
}
Upvotes: 1
Reputation: 247899
You've committed sin #1 in asynchronous programming.
You have a busy loop. Instead of waiting for GlobalV.Attatched_Elements.Count
to change, you constantly, non-stop ask "is it nonzero now? is it nonzero now? is it nonzero now? is it nonzero now? is it nonzero now? is it nonzero now? is it nonzero now? is it nonzero now?", as fast as the CPU can do it.
In other words, you're wasting a lot of execution time.
What you want to do is simply subscribe to an event telling you when Count
changes. Then, when it changes, you check if it is nonzero, and perform the necessary processing.
Upvotes: 6