Update textbox from loop in backgroundworker

后端 未结 2 1333
死守一世寂寞
死守一世寂寞 2021-01-29 08:41

I know this questions gets asked a bit (at least from what I found here so far), but I can\'t really wrap my head around it. Already tried it with the example from msdn but stil

相关标签:
2条回答
  • 2021-01-29 09:13

    outsource the loop code into a method. Inside the method you will need to use BeginInvoke to write to the TextBox

    private void DoTheLoop()
    {
        int a = 1;
        int A = 0; //variable that takes counter value (the one I want)
        int B = 0; //variable that takes counter status
        do
        {
            HS_UC_GetCounter(1, ref A, ref B);
            decimal C = (Convert.ToDecimal(A) / 100);
            textBox1.BeginInvoke(new Action(()=>{textBox1.Text = "Das ist: " + C;}));
        } while (a == 1);
    }
    

    First version using a normal Thread:

    Create a Thread and start it with the new method when the button3 is clicked

    private void button3_Click(object sender, EventArgs e)
    {
        System.Threading.Thread t = new System.Threading.Thread(()=>DoTheLoop());
        t.Start();
    }
    

    This should not block your GUI and the textbox will show the values

    Second Version using a BackgroundWorker:

    Create a BackgroundWorker and register the DoWork event:

    System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
    
    private void Form1_Load(object sender, EventArgs e)
    {
        worker.DoWork += Worker_DoWork;
    }
    

    inside the eventhandler call the same method DoTheLoop():

    private void Worker_DoWork(object sender, DoWorkEventArgs e)
    {
        DoTheLoop();
    }
    

    start the worker in the button click event:

    private void button1_Click(object sender, EventArgs e)
    {
        worker.RunWorkerAsync();
    }
    

    Same result in the end :)

    0 讨论(0)
  • 2021-01-29 09:21

    You may want to take a look a this link MSDN.

    However, a quick tip would be to register a method for the DoWork event and then execute the RunAsynchronously method.

    0 讨论(0)
提交回复
热议问题