在运行时刷新控件 [英] Refreshing Controls in runtime

查看:60
本文介绍了在运行时刷新控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 WindowsForm 并尝试从文件中导入数据,同时我想在读入新数据后立即在屏幕上显示.

I'm working on a WindowsForm and trying to import data from a file, meanwhile I'd like to display the new data on sreen as soon as I read it in.

我的基本代码如下:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Read_in();
    }

    List<Data> _list = new List<Data>();

    public void Read_in()
    {
        using (StreamReader sr = new StreamReader("in.txt"))
        {
            while (!sr.EndOfStream)
            {
                Data d = new Data
                {
                    a = sr.ReadLine()
                };
                _list.Add(d);
                Controls.Add(d.pb);
            }
        }
    }
}

class Data
{
    public string a;
    public PictureBox pb = new PictureBox()
    {
        BackColor = Color.Red
    };
}

问题是我的数据只有在 Read_in() 完成时才显示.我该怎么办?

The problem is that my data is only displayed when Read_in() is finished. How can I help this?

这里有一篇与此类似的帖子,但我看不懂:为什么不控制更新/刷新中间过程

Here's a post similar to this one, but I couldn't understand it: Why won't control update/refresh mid-process

推荐答案

那是因为正在 UI 线程中读取数据.您将不得不生成一个新线程并在其中加载数据,从而释放 UI 线程以进行更新.

Thats because the data is being read in the UI thread. You will have to spawn a new thread and load data in that, thus freeing the UI thread for updates.

正如阿列克谢建议的,这里有一点解释:

As Alexei suggested here is the bit of explanation:

请注意,只要在正常进程中执行 UI 更新,UI 线程就会被阻塞,而在多线程进程中,后台工作程序会执行所有更新,您只需要处理同步.

Note that the UI thread is blocked as long as UI update is being performed in usual process, whereas in multithreaded process, background worker does all the updation all you need to take care of is the Syncing.

请修改代码如下,让我知道:

Please modify the code as follows and let me know:

public void Read_in()
{
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.RunWorkerAsync();

}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    using (StreamReader sr = new StreamReader("in.txt"))
    {
        while (!sr.EndOfStream)
        {
            Data d = new Data
            {
                a = sr.ReadLine()
            };
            if(this.InvokeRequired)
            {
                 this.Invoke((MethodInvoker)delegate
                 {
                     _list.Add(d);
                     Controls.Add(d.pb);
                 });

            }
            else
            {
                 _list.Add(d);
                 Controls.Add(d.pb);

            }
        }
    }
}

这篇关于在运行时刷新控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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