C# - 填充面板与BackgroundWorker的控制 [英] C# - Populating Panel with controls from BackgroundWorker

查看:179
本文介绍了C# - 填充面板与BackgroundWorker的控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我写一个小的Twitter客户端,我使用。我使用一个大面板的组合,与代表单独鸣叫较小的面板。在每一个较小的面板,我有一个图片和一个RichTextBox。

So I am writing a small Twitter client for me to use. I am using a combination of one big panel, with smaller panels representing the individual tweets. In each smaller panel, I have a PictureBox and a RichTextBox.

现在,我的问题是,加载超过10鸣叫会导致经济放缓,因为我动态生成面板。所以,我决定做这个使用BackgroundWorker的,然后将这些面板添加到主面板。

Now, my problem is that loading more than 10 tweets causes a slowdown because I am dynamically generating the panels. So I decided to do this using a BackgroundWorker and then add those panels to the main panel.

我已经从不同的THEAD完成写作文这无数次的文本框(甚至写在上面的教程)。然而,我不能得到这个工作。我得到的错误消息:

I've done this numerous times with writing text to a textbox from a different thead(even wrote tutorials on it). Yet I cannot get this to work. I get the error message:

跨线程操作无效:控制''从比它创建的线程以外的线程访问。

代码:

List<Panel> panelList = new List<Panel>();

foreach (UserStatus friendStatus in list)
{
    PictureBox pbTweet = new PictureBox();
    // ...
    // code to set numerous properties
    // ...

    RichTextBox rtbTweet = new RichTextBox();
    // ...
    // code to set numerous properties
    // ...

   Panel panelTweet = new Panel();
    // ...
    // code to set numerous properties
    // ...

   panelTweet.Controls.Add(pbTweet);
   panelTweet.Controls.Add(rtbTweet);

   panelList.Add(panelTweet);
}

if (panelMain.InvokeRequired)
    panelMain.BeginInvoke((MethodInvoker)delegate { foreach (Panel p in panelList) { panelMain.Controls.Add(p); } });



任何人发现任何问题?

Anybody notice any problems?

推荐答案

在使用后台线程,你必须完全分离出来的检索修​​改表单控件的部分数据的部分。它修改表单控件的所有代码必须在UI线程中调用,即使它会需要一些时间做的事。有没有办法解决这。

When using a background thread, you have to completely separate out the parts that retrieve data from the parts that modify the form controls. All code that modifies the form controls must be invoked on the UI thread, even if it will take some time to do. There is no way round this.

这通常是一个很好的策略,因为,通常情况下,获取数据到内存是慢的部分,更新UI是快速的一部分(相互)。

This is normally a good strategy is because, usually, getting the data into memory is the slow part and updating the UI is the fast part (relative to each other).

在你的代码示例中,所有的代码是UI的改变一部分,所以它必须全部在UI线程中去了。

In your code example, all of the code is the UI-modification part, so it must all go in the UI thread.

编辑::要优化UI部分,你可以与呼叫尝试 SuspendLayout ResumeLayout 。

To optimise the UI part, you could experiment with calling SuspendLayout and ResumeLayout on the panels that you are modifying.

这篇关于C# - 填充面板与BackgroundWorker的控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆