I am trying to update a progress indicator in a multi-threaded environment. I know that many issues are already considering this issue, but none of the proposed solutions worked for me. Here is the basis of my code:
public static void DO_Computation(//parameters) {
It doesnβt work (the progress indicator freezes when it reaches 100%, which is normal (we can refer to the Microsoft article in this (indeed, this is not a thread-safe method of work)) Microsoft builds the site to wrap the Parallel.For loop in the Task procedure as follows :
public static void DO_Computation(//parameters) {
However, this does not work when debugging a thread directly leaves the task pane.
EDIT 2:
Basically, my problem is divided into 3 parts: Computation.cs (where DO_Computation displayed), WinForm , which is a form containing a progress bar, and MainWindow , which is a form that contains a button, which, when clicked, opens a form with a progress bar.
I do not understand what the "Task" is in this case. Because it leaves the Task area without executing Parallel.For work
Any ideas?
Thank you very much,
EDIT 3:
I updated my code with Noseratio (for him, this is a lot). However, I have the same problem as the internal code task is never executed. Now my code looks like this:
DoComputation method //Some Initilasations here Action enableUI = () => { frmWinProg.SetProgressText("Grading Transaction..."); frmWinProg.ChangeVisibleIteration(true); }; Action<Exception> handleError = (ex) => { // error reporting MessageBox.Show(ex.Message); }; var cts = new CancellationTokenSource(); var token = cts.Token; Action cancel_work = () => { frmWinProg.CancelTransaction(); cts.Cancel(); }; var syncConext = SynchronizationContext.Current; Action<int> progressReport = (i) => syncConext.Post(_ => frmWinProg.SetIteration(i,GrpModel2F.NumOfSim, true), null); var task = Task.Factory.StartNew(() => { ParallelLoopResult res = Parallel.For<LocalDataStruct>(1,NbSim, options, () => new DataStruct(//Hold LocalData for each thread), (iSim, loopState, DataStruct) => //Business Logic if (token.IsCancellationRequested) { loopState.Stop(); } progressReport(iSim); //Business Logic return DataStruct; }, (DataStruct) => //Assiginig Results; });//Parallel.For end }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.ContinueWith(_ => { try { task.Wait(); } catch (Exception ex) { while (ex is AggregateException && ex.InnerException != null) ex = ex.InnerException; handleError(ex); } enableUI(); }, TaskScheduler.FromCurrentSynchronizationContext
());
Note that the Do_Comput function itself is called from the form on which BackGroundWorker works.