简体   繁体   English

如何在 c# 中使 foreach 循环更快?

[英]How to make a foreach loop faster in c#?

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.我的 timer_tick 方法中有这段代码每 10 毫秒调用一次它运行正常,除非我向列表中添加更多控件。

I tried running it in a thread with Thread.sleep in a while() loop, but it seemed to freeze my whole form.我尝试在 while() 循环中使用 Thread.sleep 在线程中运行它,但它似乎冻结了我的整个表单。

How can i make this code run faster and change position of my controls?我怎样才能使这段代码运行得更快并更改我的控件的 position? 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 imgur 表格滞后展示

maybe I should use gdi+ instead?也许我应该改用 gdi+? 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我尝试在这个问题的单独线程中运行代码: 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) (听说使用 FOR 循环而不是 foreach 更快,但在这种情况下并没有真正的区别)

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.您可以尝试在循环中调用窗体上的SuspendLayoutResumeLayout ,这样它就不会为操作的每个控件更新自身……但除此之外,如果它没有帮助,可能没有好的方法可以使它更快。

Instead of using multiple PictureBox es 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 .不要在为每个音符设置动画的表单上使用多个PictureBox es,而是考虑将移动音符矩形的整个场景绘制到单个Graphics上,然后再渲染到单个PictureBox上。 This also has the handy property of being able to be rendered entirely deterministically, so you can time it exactly to your audio.这也具有能够完全确定地呈现的方便属性,因此您可以将它精确地计时到您的音频。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM