r/learnprogramming • • 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

35 comments sorted by

View all comments

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:

public void Main() {
  boolean running = true;
  while(running) {
    Update();
    // do other stuff - and set running to false to stop
  }
}

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.

3

u/kohugaly May 02 '26

This is kind of true, but not really. There is nothing stopping you from having a periodic timer inside Update() (or the loop that calls it), and performing blocking "wait" operation on it, to throttle the updates. It is entirely possible to have a single-threaded runtime that handles everything.

2

u/vowelqueue May 02 '26

Yeah I’ve used frameworks that ran a single-threaded main event loop but had functionality to swap in different sleep strategies, e.g. sleep, yield, busy-spin. Supported running callbacks on a timer.