简体   繁体   中英

c#.net blocked when i work Background

My problem is that I want the form still display data when it increases but the form is blocked and I cannot do anything with it. This is my code :

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";

        }
    }
}

How I can prevent form from blocking?

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

Split your working cycle into steps by utilizing timer

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

or put work into thread (by using Thread , BackgroundWorker or Task ), but then you must use Invoke / BeginInvoke when updating something in the user interface (accessing controls).

You can do this to get a responsive 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");
     });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM