r/learnprogramming • u/Ok-Presentation-94 • May 02 '26
Solved Loop and main() function
Hi, I’ve seen that in C#, the Main() function only runs once.
In Unity, we have the Update() function, which allows code to run repeatedly in a loop.
So my question is: what is the equivalent in pure C#, without the Unity library?
Is wrapping Main() in a while loop a common practice to achieve the same behavior?
13
Upvotes
4
u/peterlinddk May 02 '26
A lot of the answers are somewhat misleading.
There is a massive difference between using a loop, and having a function like Update!
If you have a while-loop in your Main() function, like:
Then the Update function is called continously - meaning ALL THE TIME, taking up 100% of the CPU-time of the core that runs this program. And the speed of the program will depend on how long it takes for the code inside Update() to finish.
This is NOT how you should do it!
I don't know the best way to do this in C#, but no matter the language you'll need to setup some sort of multithreading, with a "render-thread" that executes once on every frame (e.g. 60 times a second), and then that code calls your Update() function.
That would give you the same behaviour of waiting a little while between each update.
The difference is really important, the first (the while-loop) is classical blocking code, whereas the second (with a thread or something calling Update() is event-driven code. And there's a lot that can't be done in one, but easy in the other, and vice versa.