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
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
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...
(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...
ASKER
Hi kaufmed,
Thanks,
You mean I can call RunWorkerAsync() again in the backgroundworkcompleted?
JT
Thanks,
You mean I can call RunWorkerAsync() again in the backgroundworkcompleted?
JT
Yes you can.
ASKER
Hi,
when I call in the workcomplete : program crashes.
JT
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...
ASKER
Hi,
Could you give me a sample where it can do as you told me?
Thanks,
JT
Could you give me a sample where it can do as you told me?
Thanks,
JT
ASKER
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.Selection Start = 0;
this.textMessage.Selection Length = 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.Initializ ation;
stopWatch = new Stopwatch();
stopWatch.Reset();
stopWatch.Start();
bgw.RunWorkerAsync(fw);
}
catch (Exception except)
{
var outcome = MessageBox.Show(except.Mes sage, "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.Messag e);
sw.Close();
fs.Close();
}
}
}
//
// process event after detection of panel
//
private void ProcessEventNotification(s tring 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.BridgeSta te;
}));
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_Por ts_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_NotificationMess age(object sender, NotificationMessages m)
{
//
// to show another form to display messages after detection of panel
//
if (m.ToString().Equals("Pane l_Detectio n_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.ToStr ing());
}
}
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.FirmwareDownl oadProgres s += new FirmwareDownloadProgressDe legate(Adt 42To45_Fir mwareDownl oadProgres s);
fw.Adt42To45.NotificationM essage += new NotificationMessageDelegat e(Adt42To4 5_Notifica tionMessag e);
#if DEBUG
fw.Adt42To45.DebugEnabled = true;
#endif
// to handle boot recovery
if (fw.flashState == FlashUploadState.BootState )
{
FirmwareUpdateResults result2 = fw.Adt42To45.DownloadFirmw are(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.DownloadFirmw are(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.DownloadFirmw are(fw.fMe mBridge.ms , fw.fMemBooster.ms, fw.fMemFirmware.ms);
fw.result = result;
e.Result = fw;
}
}
catch (Exception except)
{
var outcome = MessageBox.Show(except.Mes sage, "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_FirmwareDownload Progress(o bject sender, int value)
{
if (fw.up.progressUpload.Invo keRequired )
{
fw.up.progressUpload.Invok e(new MethodInvoker(delegate() { Adt42To45_FirmwareDownload Progress(s ender, value); }));
return;
} // if
fw.up.progressUpload.Value = value;
fw.up.progressUpload.Refre sh();
fw.up.progressUpload.Updat e();
}
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void bgw_RunWorkerCompleted(obj ect sender, RunWorkerCompletedEventArg s e)
{
FirmWare fw = e.Result as FirmWare;
switch (fw.result)
{
case (FirmwareUpdateResults.Suc cess):
this.Invoke(new MethodInvoker(delegate ()
{
Complete c = new Complete();
c.Show();
this.Hide();
}));
break;
case (FirmwareUpdateResults.Fai led):
switch (fw.flashState)
{
case FlashUploadState.Initializ ation:
Dialog di = new Dialog();
di.textError.Text = fw.NotificationMsg + "\r\nPlease contact tech support (888) 721-6612 for assistance";
di.Show();
break;
case FlashUploadState.BridgeSta te:
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.Abo rted):
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
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.Selection
this.textMessage.Selection
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.Initializ
stopWatch = new Stopwatch();
stopWatch.Reset();
stopWatch.Start();
bgw.RunWorkerAsync(fw);
}
catch (Exception except)
{
var outcome = MessageBox.Show(except.Mes
if (outcome == DialogResult.OK)
{
if (fw.Adt42To45 != null)
fw.Adt42To45.AbortProcess(
FileStream fs = new FileStream(@"error.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(except.Messag
sw.Close();
fs.Close();
}
}
}
//
// process event after detection of panel
//
private void ProcessEventNotification(s
{
switch (msg)
{
case "Bridge_Start":
this.Invoke(new MethodInvoker(delegate
{
fw.up.textMessage2.Text = "Step 1: Uploaded File (1 of 3) ... " ;
fw.flashState = FlashUploadState.BridgeSta
}));
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_Por
{
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_NotificationMess
{
//
// to show another form to display messages after detection of panel
//
if (m.ToString().Equals("Pane
{
this.Invoke(new MethodInvoker(delegate()
{
fw.up.Show();
this.Hide();
}));
}
// display messages sent by Flashworker object
if (fw.up.Visible == true)
{
ProcessEventNotification(m
}
else
{
ProcessInitMessage(m.ToStr
}
}
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.FirmwareDownl
fw.Adt42To45.NotificationM
#if DEBUG
fw.Adt42To45.DebugEnabled = true;
#endif
// to handle boot recovery
if (fw.flashState == FlashUploadState.BootState
{
FirmwareUpdateResults result2 = fw.Adt42To45.DownloadFirmw
fw.result = result2;
e.Result = fw;
}
// to handle app recovery
else if (fw.flashState == FlashUploadState.AppState)
{
FirmwareUpdateResults result2 = fw.Adt42To45.DownloadFirmw
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.DownloadFirmw
fw.result = result;
e.Result = fw;
}
}
catch (Exception except)
{
var outcome = MessageBox.Show(except.Mes
if (outcome == DialogResult.OK)
{
if (fw.Adt42To45 != null)
fw.Adt42To45.AbortProcess(
FileStream fs = new FileStream(@"error.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Worker_class
sw.Close();
fs.Close();
}
}
}
//
// get percentage completion from FlashWorker
// and show it on the progress bar
//
void Adt42To45_FirmwareDownload
{
if (fw.up.progressUpload.Invo
{
fw.up.progressUpload.Invok
return;
} // if
fw.up.progressUpload.Value
fw.up.progressUpload.Refre
fw.up.progressUpload.Updat
}
private void bgw_ProgressChanged(object
{
}
private void bgw_RunWorkerCompleted(obj
{
FirmWare fw = e.Result as FirmWare;
switch (fw.result)
{
case (FirmwareUpdateResults.Suc
this.Invoke(new MethodInvoker(delegate ()
{
Complete c = new Complete();
c.Show();
this.Hide();
}));
break;
case (FirmwareUpdateResults.Fai
switch (fw.flashState)
{
case FlashUploadState.Initializ
Dialog di = new Dialog();
di.textError.Text = fw.NotificationMsg + "\r\nPlease contact tech support (888) 721-6612 for assistance";
di.Show();
break;
case FlashUploadState.BridgeSta
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
bgw.RunWorkerAsync(fw);
break;
case FlashUploadState.AppState:
bgw.RunWorkerAsync(fw);
break;
}
break;
case (FirmwareUpdateResults.Abo
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:
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();
}
}
ASKER
Hi,
Is it right to call console from winform? I run it I don't see it happening.
JT
Is it right to call console from winform? I run it I don't see it happening.
JT
ASKER
Hi ,
Sorry I see it in the ourtput window.
JT
Sorry I see it in the ourtput window.
JT
ASKER
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks,
JT
JT
Yes. Simply call the RunWorkerAsync() method where you would like it to start again (on the UI thread, of course).