alzinos alzinos - 2 years ago 92
C# Question

C# Console Application with a form on the side displaying live data

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();

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


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.

Answer Source

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();

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();

        f.ShowDialog(); //blocks as long as the form is open
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download