简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM