ODOTServer
asked on
Need help with background worker process called from parallel.foreach
I want to process a list of users and update a progress bar as each item s processed.
My implementation is wrong though because I receive an error :
"Cross-Thread operation not valid"
I have been directed to the link below and folowed its implementation but I am unable to circumvent the error.
I have googled a bit and tried a few different strategies but my latest iteration is receiving the same error I received before implementing background worker processes.
The method backgroundWorker1_RunWorke rCompleted is generating the exception.
I appreciate your time.
My implementation is wrong though because I receive an error :
"Cross-Thread operation not valid"
I have been directed to the link below and folowed its implementation but I am unable to circumvent the error.
I have googled a bit and tried a few different strategies but my latest iteration is receiving the same error I received before implementing background worker processes.
The method backgroundWorker1_RunWorke
I appreciate your time.
//Parallel Snippet
cancelToken = new CancellationTokenSource();
ParallelOptions parOpts = new ParallelOptions();
parOpts.CancellationToken = cancelToken.Token;
parOpts.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
try
{
Parallel.ForEach(userIDList, parOpts, user =>
{
parOpts.CancellationToken.ThrowIfCancellationRequested();
_operator.formatEmail(emailFormat, txtEmailDomain.Text, user);
UpdateProgress(); //call background processes
});
}
catch (OperationCanceledException ex)
{
MessageBox.Show("Cancellation in progress: " + ex.Message);
}
catch (OperationAbortedException ex)
{
MessageBox.Show("Process aborted. " + ex.Message);
}
//create background process
private void UpdateProgress(){
backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
this.backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_RunWorkerCompleted(
object sender,
RunWorkerCompletedEventArgs e)
{
Interlocked.Increment(ref progressCounter); //Thread safe increment
this.pgbarApplyChanges.Value = (progressCounter); //this throws the exception.
this.lblProgress.Text = (((progressCounter / userIDList.Count()) * 100).ToString() + " % Complete");
if (progressCounter == userIDList.Count)
{
btnFinish.Visible = true;
Form1.ActiveForm.Refresh();
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Wow.
Thanks! Worked like a champ.
Thanks! Worked like a champ.
https://www.experts-exchange.com/questions/24312090/Help-with-Cross-thread-operation-not-valid.html?sfQueryTermInfo=1+10+30+cross+oper+thread+valid