从类(多线程)更新 UI? [英] Update UI from Class (multithreaded)?

查看:36
本文介绍了从类(多线程)更新 UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何从 C# 中的另一个线程更新 GUI?

如何从线程类更新我的 UI?无法从线程访问更新表单控件.我想根据每个特定线程的进度更新我的用户界面.

How can I update my UI from a threaded class? Unable to access update form Controls from threads. I'd like to update my UI on the progress of each specific thread.

class MyClass
    {
        public delegate void CountChangedEventHandler(int vCount, int vIndex);
        public event CountChangedEventHandler CountChanged;

        private int count;
        private int index;

        public MyClass(int index)
        {
            this.index = index;
        }

        public int Count
        {
            get { return this.count; }
            set
            {
                this.count = value;
                if (this.CountChanged != null)
                    this.CountChanged(value, this.index);
            }
        }

        public void DoWork(object o)
        {
            for (int i = 0; i < 10000; i++)
            {
                this.Count = i;
            }
        }
    }

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

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 3; i++)
            {
                MyClass myCount = new MyClass(i);
                myCount.CountChanged += new MyClass.CountChangedEventHandler(UpdateUI);

                ListViewItem lvi = new ListViewItem();
                lvi.Text = "Thread #" + i.ToString();
                lvi.SubItems.Add("");
                listView1.Items.Add(lvi);

                ThreadPool.QueueUserWorkItem(new WaitCallback(myCount.DoWork));

            }
        }

        private void UpdateUI (int index, int count)
        {
            listView1.Items[index].SubItems[0].Text = count.ToString();
        }
    }

推荐答案

您需要使用 InvokeBeginInvoke 将 UI 访问封送回 UI 线程.

You need to use Invoke or BeginInvoke to marshal the UI access back to the UI thread.

我建议在这种情况下使用 Invoke ,因为这将阻止您的循环过于超前:

I recommend using Invoke in this instance as this will stop your loop getting too far ahead of itself:

private void UpdateUI (int index, int count)
{
  Invoke( ( MethodInvoker ) (
    () => listView1.Items[index].SubItems[0].Text = count.ToString()
  ) );
}

这篇关于从类(多线程)更新 UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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