Search code examples
c#do-whileexecution

while loop prevents other code from executing c#


I'm trying to write a drawing library. In this drawing library there is an update function that should update every frame. I do this by using a do while loop See code below:

private void UpdateCanvas()
{
    do
    {
       Canvas.PumpEvents();
       if(UserUpdateVoid != null) UserUpdateVoid();

    } while (Canvas.Exists);
}

I also have a function in which the user can set their own update function. This function is part of the SharpDraw class, see code below:

public void SetCustomUpdateFunction(Action function)
{
    Console.WriteLine("updated the user function");
    UserUpdateVoid = function;
    Console.WriteLine(UserUpdateVoid);
}

all this is called in the following way:

public class SharpCanvas
{

    private Sdl2Window Canvas;
    private GraphicsDevice GraphicsManager;
    private Action UserUpdateVoid = null;

    public SharpCanvas()
    {
        WindowCreateInfo WindowInfo = new WindowCreateInfo(
            200, 
            200, 
            100, 
            100, 
            WindowState.Normal, 
            "SharpWindow"
        );
        CreateCanvas(WindowInfo);
        UpdateCanvas();
    }
}

And the SharpDraw instance is made in the following way:

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            SharpCanvas Canvas = new SharpCanvas(200,200);
            Canvas.SetCustomUpdateFunction(Update);
        }

        private static void Update(){
            Console.WriteLine("update");
        }
    }
}

But the problem is that the Console.Writelines in the SetCustomUpdateFunction() are never executed. I guess this has to do with the fact that the while loop keeps the program from further execution. So my question is how do i keep the while loop running while still being able to execute different pieces of code? In unity they are able to do it :P

If there is something unclear let me know so i can clarify!


Solution

  • That is entirely normal. It does not mater if you are running a console application, a Windows Form or WPF/UWP application*: Only one piece of code can be executing. While one piece of code does not return, not other code can run.

    You need to add some form of Multitasking into the mix. Now that looks extremely like a Console Application and those are the last place I would advise learning Multithreading in. My personal advise is to start under Windows Forms using the BackgroundWorker. It is dated and rarely used in practice, but it can help you get up to speed with the rules and conventions. But this is one area where you can ask 10 people and get 11 Opinions.

    *Web Applciations are semi special. As they are pleasingly parallel and it helps with isolation usually each request is given their own Thread. But at least for each singular request, it still holds true.