0

So basically I have a window that displays log information such as the time and the information in a separate window called LoggerWindow. I am using this code to add items to a ListBox inside of this window:

protected void _OutputLineToConsole(LogLevel level, string line) 
    {
        foreach (Window window in Application.Current.Windows)
        {
            if (window.GetType() == typeof(LoggerWindow))
            {
                ListBoxItem itemToAdd = new ListBoxItem();
                itemToAdd.Content = line;
                ListBox lb = (window as LoggerWindow).loggerBox;
                lb.Items.Add(itemToAdd);
                ListBoxItem justAddedItem = (ListBoxItem)lb.Items[lb.Items.Count - 1];
                justAddedItem.Foreground = _LogColor(level); //gets brush color based on level
            }
        }
    }

(Note: I'm in a different file which is why this is so complicated.)

There is also code I am using to run somewhat of a "callback manager", which registers callbacks from a server and assigns handlers to them. The code is like this:

while (true)
{
    manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
}

I notice that whenever I run my application the entire thing just freezes, which I'm sure is because of the infinite loop which is necessary to get the callbacks. I commented out the while part of it, and it worked, but it only did it once, hence the need for a loop.

Is there a way to have this in an infinite loop while still being able to use my application?

kjsmita6
  • 458
  • 1
  • 6
  • 21

1 Answers1

1

Put your while(true) in the DoWork of a BackgroundWorker.

Have a look at: How to use WPF Background Worker

And it would be a good idea to use the worker's cancellation mechanism instead of the hardcoded true so that you can stop the loop when necessary, like when exiting your application.

worker = new BackgroundWorker
{
    WorkerSupportsCancellation = true
};

worker.DoWork += (sender, eventArgs) =>
{
    while (!worker.CancellationPending)
    {
         manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
    }
};

worker.RunWorkerAsync();

And when you are done, call worker.CancelAsync();

Community
  • 1
  • 1
Chris
  • 2,009
  • 1
  • 16
  • 25