Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why may C# console applications call `Application.Run()`?

Tags:

c#

windows

I have seen several examples of console applications calling Application.Run(), which starts a message loop on the current thread without a form.

https://msdn.microsoft.com/en-us/library/ms157900(v=vs.110).aspx

However, as the documentation states:

In a Win32-based or Windows Forms application, a message loop is a routine in code that processes user events, such as mouse clicks and keyboard strokes.

So, it seems that Application.Run() only applies to GUI applications.

Then what is the purpose of calling Application.Run() from console applications, and is there a smarter way of achieving the same functionality in console applications?

like image 891
Shuzheng Avatar asked Jun 29 '18 08:06

Shuzheng


1 Answers

You have to see the bigger picture, it is not Application.Run() that creates a GUI app. It is creating a window that does. The class libraries that support a window, as well as the many system and 3rd party components that interact with it, are never thread-safe. But a GUI must always deal with notifications generated from different threads, typically located in different processes or the OS.

Tricky problem, but it is one that is very common in software engineering and has a universal solution, you must solve the producer-consumer problem. Which requires a thread-safe queue, it is provided by the OS. And a loop that empties that queue and dispatches the notifications, that is what Application.Run() does.

Also the only practical way to get code to run on a specific thread. Which seems like something that should be easy to do, but is not. A thread is always busy executing code, you can't just arbitrarily interrupt it and force it to do something else, that creates horrible re-entrancy problems. The dispatcher loop is the safe spot at which a thread signals that it is idle and ready to do something else. Probably why you saw it used in a console mode app. Especially a dead-ringer when you see async/await in that code.

like image 177
Hans Passant Avatar answered Nov 01 '22 02:11

Hans Passant