c# – Parallel.Foreach和Task冲突

我在并行执行中将图像上传到云端:

// 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)";
                        }
       });

我面临的问题是,当我这样做时,UI被阻止了.原因似乎是在同一个线程中工作..

如果我将这个Parallel.ForEach包装在“Task.Factory.New”中,它就会进行异步调用,这不是我的要求.

请告诉我,如何修复UI阻止问题,以及不要使调用异步.

最佳答案 从UI线程启动时,Parallel.Foreach将阻止UI线程直到完成,因此启动的任务将排队但在UI线程返回其消息循环之前不会运行.

一种方法是使用Task.Run()在另一个线程中运行Parallel.Foreach,更好的方法是将async / await与IProgress< T>结合使用.

看到

> http://marcominerva.wordpress.com/2013/07/04/async-operations-and-progress-updates/comment-page-1/
> http://tutorials.csharp-online.net/Progress_Reporting_Patterns

点赞