Home > database >  How to make a foreach loop faster in c#?
How to make a foreach loop faster in c#?

Time:01-07

i have this piece of code in my timer_tick method called every 10 ms It runs okay unless i add more controls to the list.

I tried running it in a thread with Thread.sleep in a while() loop, but it seemed to freeze my whole form.

How can i make this code run faster and change position of my controls? Do the type of control make a difference? Should i use Panels instead of Pictureboxes?

Here's my code:

private void notepreview_Tick(object sender, EventArgs e)
{
    
    Invoke(new Action(() =>
    {
        foreach (PictureBox picbox in activeNotes)
        {
            picbox.Location = new Point(picbox.Location.X, picbox.Location.Y   1);
            //Console.WriteLine("x: "   picbox.Location.X);
            //Console.WriteLine("y: "   picbox.Location.Y);

            if (picbox.Location.Y > this.Height   5)
            {
                picbox.Dispose();
                tabPage16.Controls.Remove(picbox);
            }
        }
    }));

}

and here's how it looks in my form: (each note is spawned separately, so the lag is slowly rising which causes de-syncing with the audio and piano)

imgur form lag showcase

maybe I should use gdi instead? Would it improve the prerformance?

I tried running the code in a separate thread from this question: Accessing a form's control from a separate thread

(heard that using a FOR loop instead of foreach is faster, but it didnt really make a difference in this case)

CodePudding user response:

You can try calling SuspendLayout and ResumeLayout on your form around the loop so it doesn't update itself for each control manipulated... but beyond that, if it doesn't help, there's probably no good way to make this a lot faster.

Instead of using multiple PictureBoxes on your form that you animate for each note, consider drawing the entire scene of moving note rectangles onto a single Graphics that you render onto a single PictureBox. This also has the handy property of being able to be rendered entirely deterministically, so you can time it exactly to your audio.

  • Related