C#Winform,在不中断用户的情况下更新GUI元素

时间:2016-12-29 02:20:26

标签: c# multithreading winforms user-interface backgroundworker

我已经创建了一个程序,它根据numericUpDown1的值更新textBox1。它通过调用GUI线程进行更新的后台工作程序来完成。通过尝试更改文本来更改numericUpDown的值是不可能的,它会不断被文本框更新中断,但是使用向上和向下箭头可以正常工作。有没有办法更新文本框而不会中断试图修改numericUpDown值的用户?我附上了一个简单粗暴的例子,说明了我正在做的事情:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace t
{
    public partial class Form1 : Form
    {
        BackgroundWorker bw;
        public Form1()
        {
            InitializeComponent();
            bw = new BackgroundWorker();
            bw.DoWork += bw_DoWork;
            bw.RunWorkerAsync();
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            int value = 0;
            while (bw.CancellationPending == false)
            {
                this.Invoke((MethodInvoker)delegate()
                {
                    value = (int)numericUpDown1.Value;
                    textBox1.Text = value.ToString();
                });

            }
        }
    }
}

0 个答案:

没有答案