Solved

c#  backgroundworker

Posted on 2011-03-02
14
1,261 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 86

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

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 86

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 86

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 86

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

752 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