About using background worker on progress bar in C# RRS feed

  • Question

  • private void button6_Click(object sender, EventArgs e) { string MoreSetting = "OP02"; int i = 0; string DataOne = "00"; var IpAddress = "00"; StringBuilder sb = new StringBuilder(); try { sp.DiscardInBuffer(); for (i = 0; i < 100; i++) RxBuffer[i] = 0x00; sp.Write(new byte[] { SWADD }, 0, 1); Thread.Sleep(250); RxData(); if ((RxBuffer[1] == 0x06) && (RxBuffer[8] == 'C')) { by[0] = 0x81; by[1] = SWADD; by[2] = 0x90; by[3] = 0x81; sp.DiscardInBuffer(); textBox2.Text.Split('.').ToList().ForEach(u => sb.Append(u.ToString().PadLeft(3, '0'))); DataOne = sb.ToString(); IpAddress = MoreSetting + DataOne; DataToSend = ConstructData(by, IpAddress); sp.Write(DataToSend, 0, DataToSend.Length);

    MessageBox.Show("IP address update completed", "Status"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }

    Above is my code for sending some data using serial port after clicking a button. The whole progress takes around a few seconds. I'm trying to use a progress bar to show the progress while the serial port is transmitting and receiving those data.

    I've made some research and found this website: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/596b149d-edbf-4297-8ca4-4e6552d49464/

    and http://www.codeproject.com/Tips/83317/BackgroundWorker-and-ProgressBar-demo

    They use the background worker to do it but I have no idea how it can be put on my coding above. Could you guys teach me?

    • Edited by maniac7713 Thursday, August 2, 2012 7:09 AM
    Thursday, August 2, 2012 7:08 AM


  • Hi Maniac,

    Welcome to the MSDN Forum.

    I have check your code, I found your action finish time is not predictable. You send all your data in just one time, so I don't recommend you to use progress bar. 

    >>They use the background worker to do it but I have no idea how it can be put on my coding above.

    Try this code:

            BackgroundWorker worker = new BackgroundWorker();
            public Form1()
                worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            private void button1_Click(object sender, EventArgs e)
            private void worker_DoWork(Object sender, DoWorkEventArgs e)
                //your current code in button click handler
                //you can just copy it all here

    I hope this will be helpful.

    Best regards,

    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Mike Feng Thursday, August 16, 2012 9:14 AM
    Friday, August 3, 2012 7:13 AM