其他分享
首页 > 其他分享> > 避免在ui线程执行Parallel更新ui,否则会导致ui deadlocks

避免在ui线程执行Parallel更新ui,否则会导致ui deadlocks

作者:互联网

                Parallel.ForEach(source, new ParallelOptions
                {
                    MaxDegreeOfParallelism = Environment.ProcessorCount,
                    CancellationToken = CancellationToken.Token
                }, item =>
                {
                    //里面下载图片,更新到ui
                    DownImage(item);
                });

上面代码会导致ui deadlocks,需要如下图代码避免在ui线程执行parallel

Task.Run(() =>
            {
                Parallel.ForEach(source, new ParallelOptions
                {
                    MaxDegreeOfParallelism = Environment.ProcessorCount,
                    CancellationToken = CancellationToken.Token
                }, item =>
                {
                    //里面下载图片,更新到ui
                    DownImage(item);
                });
            });

 

标签:CancellationToken,deadlocks,DownImage,ProcessorCount,item,线程,ui,Parallel
来源: https://www.cnblogs.com/zsx-blog/p/14900472.html