当我工作背景时c#.net被阻止

时间:2014-04-11 11:42:24

标签: c# winforms windows-applications

我的问题是我希望表单在增加时仍显示数据,但表单被阻止,我无法用它做任何事情。 这是我的代码:

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

        private void button1_Click(object sender, EventArgs e)
        {
            while (true)
                for (int i = 1; i < 11; i++)
                       richTextBox1.Text += "here" + i + "/n";

        }
    }
}

如何阻止表单阻止?

3 个答案:

答案 0 :(得分:1)

private void Form1_Load(object sender, EventArgs e)
        {
            BackgroundWorker BWorker = new BackgroundWorker();
            BWorker.DoWork += BWorker_DoWork;
            BWorker.RunWorkerAsync();
        }

        void BWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // while(true) is meaningless.
            for (int i = 1; i < 11; i++)
            {
                Action UpdateUI = () => { richTextBox1.Text += "here" + i + "/n"; };
                this.BeginInvoke(UpdateUI);
            }
        }

答案 1 :(得分:0)

使用计时器

将您的工作周期分成几个步骤
    private int _workStep;

    private void button1_Click(object sender, EventArgs e)
    {
        _workStep = 0;
        timerWork.Start();
    }

    private void timerWork_Tick(...)
    {
         switch(workStep)
         {
             case 0:
                 ... // do something
                 if(something)
                     _workStep = 1;
             case laststep:
                 timerWork.Stop();
         }
    }

或将工作放入线程(使用ThreadBackgroundWorkerTask),但在更新内容时必须使用Invoke / BeginInvoke用户界面(访问控件)。

答案 2 :(得分:0)

您可以这样做以获得响应式ui

delegate void DisplayInvoker(string text);

private void DisplayinRichTextbox(string text)
{
    if (this.InvokeRequired)  
        this.BeginInvoke(new DisplayInvoker(DisplayinRichTextbox), text); 
        return;
    }
    richTextBox1.Text += text;
}

private void button1_Click(object sender, EventArgs e)
{
   // some synchronization would have to be done kill old 
   // pool threads when the button is hit again
   //
    ThreadPool.QueueUserWorkItem((x) =>
    {
        while (true)
           for (int i = 1; i < 11; i++)
               DisplayinRichTextbox("here" + i + "/n");
     });

}