Solved

c#  backgroundworker

Posted on 2011-03-02
14
1,251 Views
Last Modified: 2013-12-17
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
0
Comment
Question by:jtran007
  • 8
  • 5
14 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35022919
>>  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).
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35023344
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...
0
 

Author Comment

by:jtran007
ID: 35023692
Hi kaufmed,

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

JT
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35023701
Yes you can.
0
 

Author Comment

by:jtran007
ID: 35031315
Hi,

when I call in the workcomplete : program crashes.

JT
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35031348
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...
0
 

Author Comment

by:jtran007
ID: 35031981
Hi,

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

Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 35032088
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
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35032366
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

0
 

Author Comment

by:jtran007
ID: 35032735
Hi,
Is it right to call console from winform? I run it I don't see it happening.

JT
0
 

Author Comment

by:jtran007
ID: 35032741
Hi ,

Sorry I see it in the ourtput window.

JT
0
 

Author Comment

by:jtran007
ID: 35080322
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
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 35083020
If you have reference to the created object then it will not go out of scope.  The reference could be held at class level (outside the worker method), or you can pass it out in the RunWorkerCompleted() event and immediately feed it back in to the RunWorkerAsync() method.
0
 

Author Closing Comment

by:jtran007
ID: 35121658
Thanks,
JT
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question