Solved

c#  backgroundworker

Posted on 2011-03-02
14
1,231 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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
>>  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
Comment Utility
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
Comment Utility
Hi kaufmed,

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

JT
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Yes you can.
0
 

Author Comment

by:jtran007
Comment Utility
Hi,

when I call in the workcomplete : program crashes.

JT
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
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
Comment Utility
Hi,

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

Thanks,
JT
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:jtran007
Comment Utility
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
Comment Utility
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
Comment Utility
Hi,
Is it right to call console from winform? I run it I don't see it happening.

JT
0
 

Author Comment

by:jtran007
Comment Utility
Hi ,

Sorry I see it in the ourtput window.

JT
0
 

Author Comment

by:jtran007
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks,
JT
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

728 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now