从Class(多线程)更新UI?

时间:2013-01-14 16:29:40

标签: c# multithreading user-interface

  

可能重复:
  How to update the GUI from another thread in C#?

如何从线程类更新我的UI?无法从线程访问更新表单控件。我想更新我的UI,了解每个特定线程的进度。

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();
        }
    }

2 个答案:

答案 0 :(得分:1)

您需要使用InvokeBeginInvoke将UI访问权限封送回UI线程。

我建议在这个例子中使用Invoke,因为这会阻止你的循环走得太远:

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

答案 1 :(得分:0)

有多种方法可以实现这一目标。以下是几个选项:

1)BackgroundWorker - 您可以在网上找到大量有关如何使用此示例的示例,只要您只需要在此过程中将进度(整数)传递回UI,就可以接受。

2)带有计时器的消息队列 - 让您可以选择不仅仅将进度传递回UI。

以下是我编写的WPF应用程序中的选项2的示例,该应用程序将字符串传递回UI,当然,您可以将字符串替换为您想要的任何自定义对象。此外,还需要.NET 3.0或更高版本:

private static List<string> MessageQueue = new List<string>();

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DispatcherTimer messageQueueTimer = new DispatcherTimer();
    messageQueueTimer.Tick += messageQueueTimer_Elapsed;
    messageQueueTimer.Interval = new TimeSpan(1); //1 tick
    messageQueueTimer.Start();
}

protected void messageQueueTimer_Elapsed(object sender, EventArgs e)
{
    lock(MessageQueue)
    {
        //Read message from queue and remove it.
    }
}

//WriteLine can be called from any asyncronous method spawed from the UI.
public void WriteLine(string message)
{
    lock(MessageQueue)
    {
        //Insert message into the queue.        
    }
}

还有其他几种方法可以实现这一目标,但这应该可以让你开始。希望这有帮助!