Akon
Akon

Reputation: 272

Parallel.Foreach and Task conflict

I am uploading images to cloud in Parallel execution as :

// Make a TaskFactory that will use the UI thread's context
var uiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());

Parallel.ForEach(FinalFileNames,
    new ParallelOptions { MaxDegreeOfParallelism = 4 },
    path =>
    {
         count++;
         /* Calculate percentage of upload done */
         double iPercentDone = (int)(((float)count / iTotalFiles) * 100);

        // Send the progress report to the UI thread.
        uiFactory.StartNew(() =>
        UploadProgress.Value = iPercentDone;

        LblProgress.Content = count.ToString(CultureInfo.InvariantCulture)
                               + " file(s) uploaded from " + iTotalFiles +
                     " file(s)";
                        }
       });

The problem I am facing is, the UI is blocked when I am doing this. The reason seems to be working in the same thread..

If I do wrap this Parallel.ForEach in "Task.Factory.New", that its making the async calls, which is not my requirement.

Please let me know, How can I fix the UI block issue, as well as not making the calls async.

Upvotes: 4

Views: 937

Answers (1)

Bohdan
Bohdan

Reputation: 2027

The Parallel.Foreach when started from UI thread will block the UI thread until finished, so the Tasks started will queue up but will not run until UI thread returns to its message loop.

One way would be to run Parallel.Foreach in another thread using Task.Run(), better way is to use async/await in combination with IProgress<T>

See

Upvotes: 2

Related Questions