Update textbox from loop in backgroundworker

☆樱花仙子☆ 提交于 2019-12-02 12:59:20

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 :)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!