Rajeev Rajeev - 10 months ago 58
C# Question

Window Form Application is not responding

I have created an Window Form Console Application in which I am reading a file which has been written by another console application.
The other console application will write about the status of some process and the window form application will read the status and accordingly update the status text box.
I wrote the following code for above scenario.

while (true)
if ((new FileInfo(filename)).Length > 0)
Status = File.ReadAllText(filename, Encoding.ASCII);
System.IO.File.WriteAllText(filename, string.Empty);

Statustb.Text = Status;

if (Status.Equals("Data Got Loaded"))

When I am running the window form application it shows Form Not Responding but when I will comment out these codes then it will runs smoothly but for me it is important to update about the status.

Answer Source

You have to understand the architecture of a GUI application.

All interactions with the user happen on one thread.

This includes reacting to things like mouse and keyboard events etc.

If one of these events happens you can handle that event and do something in response to it.

But, until you return from the handler, the application will not be able to receive any further notifications (Windows Messages aka events).

I suspect you have the above code in either the constructor or in one or other event handler. Since you never exit (infinite loop, due to while(true) without a return or break, the operating system cannot send any further events to the application. They get put in a queue to be sent, but never get picked up.

Windows will detect this situation and give you the Not Responding dialog message.

I suggest, that, instead of having the code inside the while(true) loop, you create a Timer with a suitable Interval, and put the body of the while statement (ie the bit between the { and }, but not the while(true) itself ) in the Tick handler.