Link to home
Start Free TrialLog in
Avatar of jtran007
jtran007

asked on

c# backgroundworker

HI,

I have a backgrounworker1 running which checks the status of another object (test)whose returned value is in the backgroundWorkCompleted. Depending on this returned value, l will  call this object function test_call(A,B,C). The returned values is in the backgroundcompletedjob. That means bacgroundworker1 is automatically terminated when object test return value. Is it possible to call backgroundworker1 dowork again or I have to start another backgrounworker?
Since the test object still alive, I just call its other funcion.
Besides using backgroundworker techniques, is there other way to handle this scinario?
Thanks,
JT
Avatar of kaufmed
kaufmed
Flag of United States of America image

>>  Is it possible to call backgroundworker1 dowork again or I have to start another backgrounworker?

Yes. Simply call the RunWorkerAsync() method where you would like it to start again (on the UI thread, of course).
It sounds like you need to do more work in the DoWork() method based on the results of "test"?
(and don't really need to exit out causing the RunWorkerCompleted() event).

If you post the code we can possibly re-design it for ya...
Avatar of jtran007
jtran007

ASKER

Hi kaufmed,

Thanks,
You mean I can call RunWorkerAsync()  again in the backgroundworkcompleted?

JT
Yes you can.
Hi,

when I call in the workcomplete : program crashes.

JT
I ran a quick test previously and it worked fine for me.  You need to make sure that the logic within the worker can handle being called again.  Is everything initialized properly? etc...
Hi,

Could you give me a sample where it can do as you told me?

Thanks,
JT
Hi,

Attached is my program:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.IO;
using System.Diagnostics;

using DSC.Automation.FlashWorker;

namespace UpdatePanel
{
    public partial class UpdateProcess : Form
    {

 
        UploadingProgress up;
        Initialization init;
        FirmWare fw = null;
        Stopwatch stopWatch;

 

        public UpdateProcess()
        {
            InitializeComponent();

   
        }

 

        private void UpdateProcess_Load(object sender, EventArgs e)
        {
 
           this.textMessage.SelectionStart = 0;
           this.textMessage.SelectionLength = 0;
           timerAbort.Enabled = true;
           timerAbort.Start();
             //
            // to handle unexpected errors like memory leak, invalid stream file, ...
            //  let worker object abort
            //  record error to a file for insvestigation
            //  close application
            try
            {
                fw = new FirmWare();
                up = new UploadingProgress();
                init = new Initialization();
                ADT_42to45_FlashWorker Adt42To45 = new ADT_42to45_FlashWorker();
                fw.Adt42To45 = Adt42To45;
                fw.up = up;
                fw.init = init;
                fw.flashState = FlashUploadState.Initialization;
               
                stopWatch = new Stopwatch();
                stopWatch.Reset();
                stopWatch.Start();
                bgw.RunWorkerAsync(fw);
               
            }

            catch (Exception except)
            {
                var outcome = MessageBox.Show(except.Message, "System Exception", MessageBoxButtons.OK);

                if (outcome == DialogResult.OK)
                {
                    if (fw.Adt42To45 != null)
                       fw.Adt42To45.AbortProcess();   // tell worker class quit
                    FileStream fs = new FileStream(@"error.txt", FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine(except.Message);
                    sw.Close();
                    fs.Close();

                }
            }

        }
 
        //
        // process event after detection of panel
        //

        private void ProcessEventNotification(string msg)
        {
            switch (msg)
            {
                case "Bridge_Start":
                    this.Invoke(new MethodInvoker(delegate
                    {
                        fw.up.textMessage2.Text  = "Step 1: Uploaded File (1 of 3) ... " ;
                        fw.flashState = FlashUploadState.BridgeState;
                    }));
                    break;
                case "Bridge_Finish":
                    this.Invoke(new MethodInvoker(delegate
                    {
                        fw.up.textMessage2.Text = fw.up.textMessage2.Text + "success \r\n";
                     }));
                    break;

                case "Bootloader_Start":
                    this.Invoke(new MethodInvoker(delegate
                    {
                        fw.up.textMessage2.Text = fw.up.textMessage2.Text + "Step 2: Uploaded File (2 of 3) ... ";
                        fw.flashState = FlashUploadState.BootState;

                    }));
                    break;

 
                case "Bootloader_Finish":
                    this.Invoke(new MethodInvoker(delegate
                    {
                        fw.up.textMessage2.Text = fw.up.textMessage2.Text + "success \r\n";

                    }));
                    break;
                case "Application_Start":
                    this.Invoke(new MethodInvoker(delegate
                    {

                        fw.up.textMessage2.Text = fw.up.textMessage2.Text + "Step 3: Uploaded File (3 of 3) ...";
                        fw.flashState = FlashUploadState.AppState;

                    }));
                    break;

 
                case "Application_Finish":
                    this.Invoke(new MethodInvoker(delegate
                    {
                        fw.up.textMessage2.Text = fw.up.textMessage2.Text + "success \r\n";

                    }));
                    break;
                default:  // handle all kinds of messages
                    this.Invoke(new MethodInvoker(delegate
                    {
                        fw.NotificationMsg = msg;
                    }));
                    break;

            }
           
        }

        //
        // process message during detecting of panel
        //
        private void ProcessInitMessage(string msg)
        {

            if (msg.Equals("No_Serial_Ports_Found"))     // no serial port

            {
                this.Invoke(new MethodInvoker(delegate
                {
                    //Initialization ini = new Initialization();
                    fw.init.Show();
                    fw.init.textBox1.Text = "No Serial Port Found !!!";
                    this.Hide();
                }));

            }
            else
            {
                this.Invoke(new MethodInvoker(delegate() { textMessage.Text = textMessage.Text + "\r\n" + msg; }));
            }
        }
 

        private void Adt42To45_NotificationMessage(object sender, NotificationMessages m)
        {

            //
            // to show another form to display messages after detection of panel
            //
            if (m.ToString().Equals("Panel_Detection_Finish"))
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    fw.up.Show();
                    this.Hide();
                }));
            }

            // display messages sent by  Flashworker object

            if (fw.up.Visible == true)
            {
                ProcessEventNotification(m.ToString());
            }
            else
            {
                ProcessInitMessage(m.ToString());
            }
   

        }

        private void bgw_DoWork(object sender, DoWorkEventArgs e)
        {

            // register notification messages
            // process these messages once worker class raises these events
            //
            try
            {
                FirmWare fw = e.Argument as FirmWare;

                fw.Adt42To45.FirmwareDownloadProgress += new FirmwareDownloadProgressDelegate(Adt42To45_FirmwareDownloadProgress);

                fw.Adt42To45.NotificationMessage += new NotificationMessageDelegate(Adt42To45_NotificationMessage);

#if DEBUG
                fw.Adt42To45.DebugEnabled = true;
#endif

                // to handle boot recovery
                if (fw.flashState == FlashUploadState.BootState)
                {
                    FirmwareUpdateResults result2 = fw.Adt42To45.DownloadFirmware(null, fw.fMemBooster.ms, fw.fMemFirmware.ms);
                    fw.result = result2;
                    e.Result = fw;
                }

                // to handle app recovery
                else if (fw.flashState == FlashUploadState.AppState)
                {
                    FirmwareUpdateResults result2 = fw.Adt42To45.DownloadFirmware(null, null, fw.fMemFirmware.ms);
                    fw.result = result2;
                    e.Result = fw;
                }
                else
                {


                    // save all worker class messages to ..\bin\debug.txt if running in the debug mode
                    // for troubleshooting

                    FirmwareUpdateResults result = fw.Adt42To45.DownloadFirmware(fw.fMemBridge.ms, fw.fMemBooster.ms, fw.fMemFirmware.ms);

                    fw.result = result;

                    e.Result = fw;
                }
            }
            catch (Exception except)
            {
                var outcome = MessageBox.Show(except.Message, "Worker Class Exception", MessageBoxButtons.OK);

                if (outcome == DialogResult.OK)
                {
                    if (fw.Adt42To45 != null)
                        fw.Adt42To45.AbortProcess();   // tell worker class quit
                    FileStream fs = new FileStream(@"error.txt", FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine("Worker_class:" + except.Message);
                    sw.Close();
                    fs.Close();

                }
            }          

 

        }

        //
        // get percentage completion from FlashWorker
        // and show it on the progress bar
        //
        void Adt42To45_FirmwareDownloadProgress(object sender, int value)
        {
            if (fw.up.progressUpload.InvokeRequired)
            {
                fw.up.progressUpload.Invoke(new MethodInvoker(delegate() { Adt42To45_FirmwareDownloadProgress(sender, value); }));
                return;
            } // if
            fw.up.progressUpload.Value = value;
            fw.up.progressUpload.Refresh();
            fw.up.progressUpload.Update();

        }

        private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           
        }

        private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            FirmWare fw = e.Result as FirmWare;

             switch (fw.result)
            {
                case (FirmwareUpdateResults.Success):
                    this.Invoke(new MethodInvoker(delegate ()
                        {
 
                          Complete c = new Complete();
                          c.Show();
                          this.Hide();

 
                    }));
                   
                    break;
                case (FirmwareUpdateResults.Failed):

                    switch (fw.flashState)
                    {
                        case FlashUploadState.Initialization:
                           Dialog di = new Dialog();
                           di.textError.Text = fw.NotificationMsg + "\r\nPlease contact tech support (888) 721-6612 for assistance";
                           di.Show();
                           break;
                        case FlashUploadState.BridgeState:
                            Dialog di2 = new Dialog();
                           di2.textError.Text = fw.NotificationMsg + "\r\nPlease contact tech support (888) 721-6612 for assistance";
                           di2.Show();
                           break;
                        case FlashUploadState.BootState:  // recover bootloader
                                                                 
                                  bgw.RunWorkerAsync(fw);
                             
                           
                            break;
                        case FlashUploadState.AppState:   // recover application
                          bgw.RunWorkerAsync(fw);
                             
                             break;
                    }
                 break;
                case (FirmwareUpdateResults.Aborted):

                     Dialog di3 = new Dialog();
                    di3.textError.Text = "Abort requested";
                    di3.Show();

                  break;

            }



        }

       //
       // if taking too long, request abort to worker class
       //
        private void timerAbort_Tick(object sender, EventArgs e)
        {
            if (bgw != null && bgw.IsBusy)
            {
                timerAbort.Stop();
                bgw.CancelAsync();
            }
           
        }

 

 
      }
}
Regards,
JT
Haven't looked closely at your code yet...that's a lot to take in!

Here's a bare bones example...just puts the current time in the output window by repeatedly restarting the BackgroundWorker:
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            System.Threading.Thread.Sleep(1000);
            Console.WriteLine(DateTime.Now.ToString());
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

    }

Open in new window

Hi,
Is it right to call console from winform? I run it I don't see it happening.

JT
Hi ,

Sorry I see it in the ourtput window.

JT
Hi ,

My code is doing as follow:

1- First_dowork(): create object
2-completeWork(); that object will be terminated (? since it is out of scope)
                            I call dowork() again
3-Second_dowork(): creat object

My question is that do I have to create object again in the 2nd call ? since I register event
for this object, but I don't see the event happenedn in the second call?

Thanks,
JT
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks,
JT