I have a list of Contacts as follows.
List<string> Numbers = new List<string>();
This list can have any length of numbers in it. I want to send message to these numbers one by one and also report the progress to the user on a WinForm so I have a method like this.
private void ProcessBroadcast()
{
foreach (var number in Numbers)
{
//Send a Message here
messageWorker.RunWorkerAsync(message);
}
}
Since sending a message takes time so we opted to use BackgroundWorker to send a message. Now here the issue is we want to continue to send message to the next number in the foreach loop only when Background worker has completed.
I have implemented
messageWorker_DoWork
&
messageWorker_RunWorkerCompleted
and I am able to get the Number in messageWorker_RunWorkerCompleted method. I have done my research but couldn't find anything related to this.
private void ProcessBroadcast()
{
//foreach (var number in Numbers)
//{
// //Send a Message here
// messageWorker.RunWorkerAsync(message);
//}
messageWorker.EnableProgressReporting = true;
messageWorker.RunWorkerAsync(Numbers);
}
The DoWork
// this runs on a background pool thread
void DoWork(object sender, args)
{
var worker = sender as Backgroundworker;
var Numbers = args.Argument as IEnumerable<SomeThing>;
int percentage = 0;
foreach (var number in Numbers)
{
//Send a Message here
worker.ReportProgress(percentage, number);
// other processing on number, just don't use the UI
}
}
Your Progress and Completed eventhandlers will be executed on the main thread.
(none of this was checked by a compiler)