0

I am writing a neural network simulator application in C# WPF and would like to run the main program loop in a given ms cycle.

For this I have the following code:

while(true)
{
    if(main_cycle_watch.ElapsedMilliseconds >= main_cycle_watch_ms + target_cycle_time)
    {
        /* Refresh timer base */
        main_cycle_watch_ms = main_cycle_watch.ElapsedMilliseconds;

        /* Call main world handling method */
        WorldHandlingMain();
    }

    /* Handle window events */
    ???
}

As the while loop runs infinitely the main window events do not get the chance to be handled therefor the application is not responsive at all.

So I would like to know if there is a way to force the main window to handle its events.

alibi69
  • 13
  • 1
  • 4

1 Answers1

0

Don't run your infinite processing loop on the main UI thread, then the UI thread will be able to handle the window events and be responsive.

Also consider a different control logic for your infinite loop and run a handler method based on a timer instead.

//create a timer with an interval of 2 seconds
var timer = new Timer(2000);
timer.OnElapsed += handleTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;

private static void handleTimedEvent(Object source, ElapsedEventArgs e)
{
    WorldHandlingMain();
}
TJ Rockefeller
  • 3,178
  • 17
  • 43
  • In WPF you would usually run a DispatcherTimer, otherwise you would need to marshal the timer action to the Dispatcher of the UI thread. – Clemens Jan 25 '22 at 21:38
  • If the actions in the timer need to happen on the UI thread which it's unclear if that's a requirement. Typically I will run as much as I can not on the UI thread, and only marshal things to the UI dispatcher if required for UI updates instead of running everything on the UI thread. – TJ Rockefeller Jan 25 '22 at 21:42
  • If you read the question title, it should be obvious that the UI is supposed to be updated. Anyway, I closed the question as a duplicate. This does not need to be answered the 100th time. – Clemens Jan 25 '22 at 21:47