473,609 Members | 1,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Background worker tasks sequentially?

I'm able to use the Bacground Worker class to execute task and pain the
UI. However I want to be able to execute n tasks in order, say n1, then
n2 if there were no errors during n1, n3 so on.

I'm wondering what would be the best way to do this , do I wait in a
do...while loop for each to finish and then start another ?

thanks
Sunit

Dec 13 '06 #1
6 5956
Sunit,

That's basically what you will have to do. It seems like you have three
tasks, but you want all three to run sequentially, just not on the UI
thread. You can still use the BackgroundWorke r class for this, you just
have to do the first task with it, then the second, then the third, and so
on, and so on.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"sjoshi" <sj****@ingr.co mwrote in message
news:11******** *************@t 46g2000cwa.goog legroups.com...
I'm able to use the Bacground Worker class to execute task and pain the
UI. However I want to be able to execute n tasks in order, say n1, then
n2 if there were no errors during n1, n3 so on.

I'm wondering what would be the best way to do this , do I wait in a
do...while loop for each to finish and then start another ?

thanks
Sunit

Dec 14 '06 #2
Sunit,

In addition to what Nicholas said there is an event on the
BackgroundWorke r class that is raised when the task is complete. You
should be able to use that to your advantage.

Brian

sjoshi wrote:
I'm able to use the Bacground Worker class to execute task and pain the
UI. However I want to be able to execute n tasks in order, say n1, then
n2 if there were no errors during n1, n3 so on.

I'm wondering what would be the best way to do this , do I wait in a
do...while loop for each to finish and then start another ?

thanks
Sunit
Dec 14 '06 #3

Nicholas Paldino [.NET/C# MVP] wrote:
Sunit,

That's basically what you will have to do. It seems like you have three
tasks, but you want all three to run sequentially, just not on the UI
thread. You can still use the BackgroundWorke r class for this, you just
have to do the first task with it, then the second, then the third, and so
on, and so on.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"sjoshi" <sj****@ingr.co mwrote in message
news:11******** *************@t 46g2000cwa.goog legroups.com...
I'm able to use the Bacground Worker class to execute task and pain the
UI. However I want to be able to execute n tasks in order, say n1, then
n2 if there were no errors during n1, n3 so on.

I'm wondering what would be the best way to do this , do I wait in a
do...while loop for each to finish and then start another ?

thanks
Sunit
Ok thanks I need to run a background task for each row ina dset. So I
tried this:

foreach (DAO.DAODatabas e.DatabaseRow backupEntry in
_srvBackupDSet. Database)
{
InitAndStartBac kgroundWorker(b ackupEntry);
while (!_lastRunFinis hed)
{
Thread.Sleep(50 0);
}
if (!_lastRunOk)
break;
}
private void InitAndStartBac kgroundWorker(D AO.DAODatabase. DatabaseRow
backupRow)
{
worker = new BackgroundWorke r();
worker.WorkerRe portsProgress = true;

//Set background worker
worker.DoWork += new DoWorkEventHand ler(worker_DoWo rk);
worker.Progress Changed += new
ProgressChanged EventHandler(wo rker_ProgressCh anged);
worker.RunWorke rCompleted += new
RunWorkerComple tedEventHandler (worker_RunWork erCompleted);

//Start Backup
worker.RunWorke rAsync(backupRo w);
}

void worker_DoWork(o bject sender, DoWorkEventArgs e)
{
_lastRunFinishe d = false;
_backupMgr.Perc entCompleted += new
PercentEventHan dler(_backupMgr _PercentComplet ed);
BackgroundWorke r theWorker = sender as BackgroundWorke r;
DoBackup((DAO.D AODatabase.Data baseRow)e.Argum ent);
}

void worker_RunWorke rCompleted(obje ct sender,
RunWorkerComple tedEventArgs e)
{
if (e.Error != null)
{
_lastRunOk = false ;
UpdateGridForEr ror(e.Error);
}
else
_lastRunOk = true;
_lastRunFinishe d = true;
}
void worker_Progress Changed(object sender, ProgressChanged EventArgs e)
{
//code to UpdateGrid progress bar
}

However now the UI freezes and the 1st job itself never completes; i.e
the run worker_RunWorke rCompleted event is never raised.

It works fine if I just pass a single row.

thanks
Sunit

Dec 14 '06 #4
It looks like you are waiting on a loop until the processing is done.
You should be letting the events that the BackgroundThrea d fires tell you
when you are done instead of waiting for the variables to be set (which you
are doing the wrong way, since you are not locking access to them).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"sjoshi" <sj****@ingr.co mwrote in message
news:11******** *************@f 1g2000cwa.googl egroups.com...
>
Nicholas Paldino [.NET/C# MVP] wrote:
>Sunit,

That's basically what you will have to do. It seems like you have
three
tasks, but you want all three to run sequentially, just not on the UI
thread. You can still use the BackgroundWorke r class for this, you just
have to do the first task with it, then the second, then the third, and
so
on, and so on.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"sjoshi" <sj****@ingr.co mwrote in message
news:11******* **************@ t46g2000cwa.goo glegroups.com.. .
I'm able to use the Bacground Worker class to execute task and pain the
UI. However I want to be able to execute n tasks in order, say n1, then
n2 if there were no errors during n1, n3 so on.

I'm wondering what would be the best way to do this , do I wait in a
do...while loop for each to finish and then start another ?

thanks
Sunit
Ok thanks I need to run a background task for each row ina dset. So I
tried this:

foreach (DAO.DAODatabas e.DatabaseRow backupEntry in
_srvBackupDSet. Database)
{
InitAndStartBac kgroundWorker(b ackupEntry);
while (!_lastRunFinis hed)
{
Thread.Sleep(50 0);
}
if (!_lastRunOk)
break;
}
private void InitAndStartBac kgroundWorker(D AO.DAODatabase. DatabaseRow
backupRow)
{
worker = new BackgroundWorke r();
worker.WorkerRe portsProgress = true;

//Set background worker
worker.DoWork += new DoWorkEventHand ler(worker_DoWo rk);
worker.Progress Changed += new
ProgressChanged EventHandler(wo rker_ProgressCh anged);
worker.RunWorke rCompleted += new
RunWorkerComple tedEventHandler (worker_RunWork erCompleted);

//Start Backup
worker.RunWorke rAsync(backupRo w);
}

void worker_DoWork(o bject sender, DoWorkEventArgs e)
{
_lastRunFinishe d = false;
_backupMgr.Perc entCompleted += new
PercentEventHan dler(_backupMgr _PercentComplet ed);
BackgroundWorke r theWorker = sender as BackgroundWorke r;
DoBackup((DAO.D AODatabase.Data baseRow)e.Argum ent);
}

void worker_RunWorke rCompleted(obje ct sender,
RunWorkerComple tedEventArgs e)
{
if (e.Error != null)
{
_lastRunOk = false ;
UpdateGridForEr ror(e.Error);
}
else
_lastRunOk = true;
_lastRunFinishe d = true;
}
void worker_Progress Changed(object sender, ProgressChanged EventArgs e)
{
//code to UpdateGrid progress bar
}

However now the UI freezes and the 1st job itself never completes; i.e
the run worker_RunWorke rCompleted event is never raised.

It works fine if I just pass a single row.

thanks
Sunit

Dec 14 '06 #5

Nicholas Paldino [.NET/C# MVP] wrote:
It looks like you are waiting on a loop until the processing is done.
You should be letting the events that the BackgroundThrea d fires tell you
when you are done instead of waiting for the variables to be set (which you
are doing the wrong way, since you are not locking access to them).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"sjoshi" <sj****@ingr.co mwrote in message
news:11******** *************@f 1g2000cwa.googl egroups.com...

Nicholas Paldino [.NET/C# MVP] wrote:
Sunit,

That's basically what you will have to do. It seems like you have
three
tasks, but you want all three to run sequentially, just not on the UI
thread. You can still use the BackgroundWorke r class for this, you just
have to do the first task with it, then the second, then the third, and
so
on, and so on.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"sjoshi" <sj****@ingr.co mwrote in message
news:11******** *************@t 46g2000cwa.goog legroups.com...
I'm able to use the Bacground Worker class to execute task and pain the
UI. However I want to be able to execute n tasks in order, say n1, then
n2 if there were no errors during n1, n3 so on.

I'm wondering what would be the best way to do this , do I wait in a
do...while loop for each to finish and then start another ?

thanks
Sunit
Ok thanks I need to run a background task for each row ina dset. So I
tried this:

foreach (DAO.DAODatabas e.DatabaseRow backupEntry in
_srvBackupDSet. Database)
{
InitAndStartBac kgroundWorker(b ackupEntry);
while (!_lastRunFinis hed)
{
Thread.Sleep(50 0);
}
if (!_lastRunOk)
break;
}
private void InitAndStartBac kgroundWorker(D AO.DAODatabase. DatabaseRow
backupRow)
{
worker = new BackgroundWorke r();
worker.WorkerRe portsProgress = true;

//Set background worker
worker.DoWork += new DoWorkEventHand ler(worker_DoWo rk);
worker.Progress Changed += new
ProgressChanged EventHandler(wo rker_ProgressCh anged);
worker.RunWorke rCompleted += new
RunWorkerComple tedEventHandler (worker_RunWork erCompleted);

//Start Backup
worker.RunWorke rAsync(backupRo w);
}

void worker_DoWork(o bject sender, DoWorkEventArgs e)
{
_lastRunFinishe d = false;
_backupMgr.Perc entCompleted += new
PercentEventHan dler(_backupMgr _PercentComplet ed);
BackgroundWorke r theWorker = sender as BackgroundWorke r;
DoBackup((DAO.D AODatabase.Data baseRow)e.Argum ent);
}

void worker_RunWorke rCompleted(obje ct sender,
RunWorkerComple tedEventArgs e)
{
if (e.Error != null)
{
_lastRunOk = false ;
UpdateGridForEr ror(e.Error);
}
else
_lastRunOk = true;
_lastRunFinishe d = true;
}
void worker_Progress Changed(object sender, ProgressChanged EventArgs e)
{
//code to UpdateGrid progress bar
}

However now the UI freezes and the 1st job itself never completes; i.e
the run worker_RunWorke rCompleted event is never raised.

It works fine if I just pass a single row.

thanks
Sunit
Yes I forgot about the locking...will that be the reason for freeeze ?
I do set the variables in the RunWorkerComple ted event so that I can
know when to start another one and as such I can create a new
BackgroundWorke r in the InitAndStart method. Is this the correct way to
start next task ?
Can you please let me know what I'm doing wrong here (pseudo code...)

thanks
Sunit

Dec 14 '06 #6
"sjoshi" <sj****@ingr.co mwrote in message
news:11******** *************@t 46g2000cwa.goog legroups.com...
I'm able to use the Bacground Worker class to execute task and pain the
UI. However I want to be able to execute n tasks in order, say n1, then
n2 if there were no errors during n1, n3 so on.

I'm wondering what would be the best way to do this , do I wait in a
do...while loop for each to finish and then start another ?
If you want tasks processed sequentially, you need a queue of some sort.

One way to do this would be to take advantage of the suggestions offered so
far. You would add the tasks to the queue, and then use the event Brian
mentions to know when to start a new task thread.

Alternatively, you could just keep a single background thread running that
pulls tasks from the queue as long as the queue isn't empty. Once the queue
is empty, the background thread could wait on an EventWaitHandle that the
main thread would set any time it adds something to the queue.

In either approach, you can include logic to check the results of the
previous task before starting the next one and just abort the whole thing if
an error occurs.

For sure, the thread synchronization you've tried in the code you posted
already is wrong. It appears that you're polling (which is why the main UI
freezes up...you never leave the loop until all tasks are done), and you're
checking an unsynchronized flag (which isn't thread-safe).

Pete
Dec 14 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
1992
by: bonk | last post by:
I have an application that needs to perform some background work, i.e. Logging, wich must not block the main thread. How would I basically design such a scenario? It is obvious that I should do that on an extra thread but I think it is a bad idea to spawn a new thread everytime a log-message is written and let it die once the message was written. But how do I keep a thread alive and trigger the log-messages and pass the string to that...
8
5350
by: =?Utf-8?B?R3JlZyBMYXJzZW4=?= | last post by:
I'm trying to figure out how to modify a panel (panel1) from a backgroundworker thread. But can't get the panel to show the new controls added by the backgroundwork task. Here is my code. In this code there is a panel panel1, that I populate with a lable in the foreground. Then when I click on "button1" a backgroundworker thread in async mode is started. When the backgoundworker thread completes the thread returns a panel to populate...
3
2296
by: Kevin | last post by:
Using this: http://msdn2.microsoft.com/en-us/library/3dasc8as(VS.80).aspx as an example I have a question concerning the reuse of objects. In the example 10 instances of the Fibonacci class are made and then all put in the threadpool at once, which is well within the limits of the threadpool. However, what happens if you want to do 10,000 Fibonacci calculations
13
10210
by: deciacco | last post by:
How can I have access to the items collection of a listview control on my form from a background thread? I know I need delegates to update the listview control and I have those calls in the foreach loop, but I'm not sure how to access the items collection. foreach (ListViewItem li in this.listview1.Items) { Invoke(new deleg(updatectrl), new object { param });
4
2408
by: csharpula csharp | last post by:
Hello, Can you please tell me if I should use the background worker in the following way: if (worker.IsBusy) worker.CancelAsync(); (or I can avoid this if)? And in case I want to restart the background worker ,should I do it this way? worker.RunWorkerAsync();
0
2996
by: Smokey Grindel | last post by:
I have a search function that runs in a background worker which can run long.. I want the user to be able to cancel that then run another search... but sometimes it throws an exception saying System.InvalidOperationException: This BackgroundWorker is currently busy and cannot run multiple tasks concurrently. What I did before the search button was pressed again was check if the worker is busy and if it is cancel the current search then...
8
10936
by: Analizer1 | last post by:
From what im reading about backgroundworker thread it seems it can only have 1 thread at a time is this correct tks
7
3012
by: csharpula csharp | last post by:
Hello, I got a question regarding the usage of background worker. How can I run few threads via background worker with different objects as parameter each time. I understood that I can't do this: for (int i = 0; i < inputNum; i++) { string param = i.ToString();
1
2024
by: Infog | last post by:
I am trying to code a simple background workers class without needing to use the backgroundworker object on a form. This would allow me to use a background worker in any class without writing much additional code. Is it possible to pass in the name of a sub at runtime instead of hard-coding it? To do this I would replace onDoWork and onProgressChanged below and use (Byval onWorkSub as SomeKindOfObject?, Byval onProgressChangedSub as...
0
8095
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8588
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8410
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6068
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4037
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4103
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2541
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.