Search code examples
c#winformsinvoke

Using Foreach Loop inside of Invoke


Don't mind the variables like GameObject. Those are custom variables of mine.

I have a thread, and I need to access a list variable inside the UI thread.

public void MainLoop(){
        while (true)
        {
            this.Invoke(new MethodInvoker(() =>


            foreach(GameObject ob in mygame.scenes[CurrentScene].objects){

              //run code here

            }


            ));
        }

    }

This throws the error, "} expected". I cannot seem to figure out how to fix this. Does anyone know how to run a foreach loop inside a Control Invoke?


Solution

  • You just need an additional set of {}. Here your code is formatted so it is readable with the braces added.

    public void MainLoop()
    {
      while (true)
      {
        this.Invoke(new MethodInvoker(() =>
                    {
                      foreach(GameObject ob in mygame.scenes[CurrentScene].objects)
                      {
                        //run code here
                      }
                    }
                    ));
      }
    }