繁体   English   中英

自定义控件属性-C#,表单

[英]Custom Controls Properties - C# , Forms

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

因此,在每个计时器刻度上,我都会添加一个控件,更改控件按钮文本,然后将其添加到flowlayout面板中,

我在每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
    }
}

它每秒发生10次,因为您要告诉它。

一秒钟有1000毫秒

如果您每100毫秒执行一次操作,则您每秒执行10次操作。


好的,这里发生了一些事情。 首先,您需要维护要更新的各种控件的处理程序或名称。 可以通过定义的对象或使用FINDCONTROL(“ ControlName”)来完成。

现在,由于您在计时器控件中访问该控件的问题,这是由于THREADS! Timer_Elapsed事件中的代码发生在单独的线程上,因此,要影响UI,您需要使代码线程安全。

考虑以下对象:

// The declaration of the textbox.
private TextBox m_TextBox;
public delegate void UpdateTextCallback(string text);

然后,您将拥有执行实际更改的方法

// Updates the textbox text.
private void UpdateText(string text)
{
  // Set the textbox text.
  m_TextBox.Text = text;
}

然后在单独的线程中,通过

m_TextBox.Invoke(new UpdateTextCallback(this.UpdateText),  new object[]{”Text generated on non-UI thread.”});

暂无
暂无

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

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