1

I have a console application that takes in live data from a database, and acts upon it in real time, the bulk of my Main method is within a while(true) loop. I need a form in the background which displays one part of the data that available during the loop. I want it refreshing every time the program completes a loop showing the new value. I've added a form to my project, and added the following code to my initialisation section:

DataDisplay dataDisplay = new DataDisplay();
dataDisplay.Show();

above the Main declaration. This makes the window pop up, but whenever I mouse over it my cursor turns into the Microsoft loading blue circle. The rest of my program runs fine, current functionality remains, just the form isn't happy. Variants of

Application.Run(dataDisplay);
dataDisplay.ShowDialog();

Cause my program to hang on the above lines without progressing to the while loop as the applications doesn't end.

I haven't started building the functionality for populating my form as it doesn't seem to want to behave.

What am I doing wrong, I am relatively new to C# and Winforms both.

alzinos
  • 71
  • 10
  • Does this help: http://stackoverflow.com/questions/11500563/winform-multithreading-use-backgroundworker-or-not ? – Bart De Boeck Nov 03 '16 at 14:29
  • You must use a `BackgroundWorker` for the data retrieving part. You have an infinite loop in your main form if i understand it right, so the main thread is busy and cant draw anything in your second form – Pikoh Nov 03 '16 at 14:29
  • 3
    There's no reason to use BGW, it's obsolete. Use Task.Run to run the long-running job from inside the form, and use `Progress` to send messages to the form – Panagiotis Kanavos Nov 03 '16 at 14:31
  • You might consider writing to the console instead of form. You can write to specific areas of the window, you don't have to let everything scroll away. – Crowcoder Nov 03 '16 at 14:33
  • Well, if you are stuck to .net 3.5 as i am in some projects, you must use a BGW. But you are right, it's better to use a Task :) – Pikoh Nov 03 '16 at 14:33

1 Answers1

1

You are blocking your main thread, that's why the gui can't update or react to any user input. I would suggest moving the while(true) loop to a different thread.

Here's a short example:

class MyForm : Form
{
    public Label label;

    public MyForm()
    {
        label = new Label();
        this.Controls.Add(label);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyForm f = new MyForm();

        (new Task(() =>
        {
            //your loop
            while (true)
            {
                f.Invoke(new Action(() =>
                {
                    f.label.Text = (new Random()).Next().ToString();
                }));
                Console.WriteLine("working...");
                Thread.Sleep(500);
            }
        })).Start();

        f.ShowDialog(); //blocks as long as the form is open
    }
}
sknt
  • 963
  • 6
  • 16