c# - 自定义控件属性 - C#、窗体

标签 c# winforms user-controls

我正在向我的 flowlayoutpanel 添加自定义控件,它是一种外汇数据,每秒刷新一次,

所以在每个计时器滴答时,我添加一个控件,更改控件按钮文本,然后将其添加到流布局面板,

我在每 100 毫秒计时器滴答时执行一次,

它占用了太多 CPU,

这是我的自定义控件。

public partial class UserControl1 : UserControl
{
    public void displaydata(string name, string back3price, string back3, string back2price, string back2, string back1price, string back1, string lay3price, string lay3 , string lay2price, string lay2, string lay1price, string lay1)
    {
        lblrunnerName.Text = name.ToString();

        btnback3.Text = back3.ToString() + "\n" + back3price.ToString();
        btnback2.Text = back2.ToString() + "\n" + back2price.ToString();
        btnback1.Text = back1.ToString() + "\n" + back1price.ToString();

        btnlay1.Text = lay1.ToString() + "\n" + lay1price.ToString();
        btnlay2.Text = lay2.ToString() + "\n" + lay2price.ToString();
        btnlay3.Text = lay3.ToString() + "\n" + lay3price.ToString();
    }    

下面是我如何添加控件;

private void timer1_Tick(object sender, EventArgs e)
{
    localhost.marketData[] md;

    md = ser.getM1();

    flowLayoutPanel1.Controls.Clear();

    foreach (localhost.marketData item in md)
    {
        UserControl1 ur = new UserControl1();
        ur.Name = item.runnerName + item.runnerID;
        ur.displaydata(item.runnerName, item.back3price, item.back3, item.back2price, item.back2, item.back1price, item.back1, item.lay3price, item.lay3, item.lay2price, item.lay2, item.lay1price, item.lay1);

        flowLayoutPanel1.SuspendLayout();
        flowLayoutPanel1.Controls.Add(ur);
        flowLayoutPanel1.ResumeLayout();
    }
}

现在它在每次发送时发生 10 次,占用了我 Core2Duo CPU 的 60%。 我想快速刷新它,我需要一些优化技巧

有没有其他方法,我可以第一次添加控件,然后在每次刷新或定时器滴答时更改运行时自定义控件按钮的文本

我正在使用 C# .Net

最佳答案

为了多次访问控件,您需要使变量的作用域大于仅使用 tick 方法。请参阅使其成为类变量的示例。您还可以将控件构造函数放在表单构造函数中,然后 tick 方法将只用于更改数据。

public MyForm : Form
{
    private UserControl _userControl = null;
    ...
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (_userControl == null)
            //make control
        //set control data
    }
}

关于c# - 自定义控件属性 - C#、窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2935271/

相关文章:

c# - C#判断文件是否被修改

c# - 在数组中查找长度等于 P *(元素总和)的子数组

c# - OpenFileDialog 正在最小化父表单

c# - 创建和使用协变和可变列表(或潜在的解决方法)

c# - 在 MVC 中使用 Web API DelegatingHandler

c# - 为单个控件多次出现 Handle Created

c# - 计算一条线的精确像素

c# - 在 UserControl 中按下 Enter 时不会触发 KeyDown 事件

c# - 我可以迭代数据源吗?

c# - 公开 MVVM 中内置的用户控件的属性