为什么我试图将所有图像从硬盘转移到列表时出现异常?

时间:2016-12-26 11:32:11

标签: c# .net winforms

在form1构造函数中:

imageslist = Directory.EnumerateFiles(dir, "*.bmp", SearchOption.AllDirectories)
    .AsParallel()
    .Select(path => new Bitmap(path))
    .Select(bmp => ResizeImage(bmp, 100, 100))
    .ToList();

例外是:

未处理的类型' System.AggregateException'发生在System.Core.dll

其他信息:发生了一个或多个错误。

System.AggregateException was unhandled
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=System.Core
  StackTrace:
       at System.Linq.Parallel.QueryTaskGroupState.QueryEnd(Boolean userInitiatedDispose)
       at System.Linq.Parallel.SpoolingTask.SpoolStopAndGo[TInputOutput,TIgnoreKey](QueryTaskGroupState groupState, PartitionedStream`2 partitions, SynchronousChannel`1[] channels, TaskScheduler taskScheduler)
       at System.Linq.Parallel.DefaultMergeHelper`2.System.Linq.Parallel.IMergeHelper<TInputOutput>.Execute()
       at System.Linq.Parallel.MergeExecutor`1.Execute()
       at System.Linq.Parallel.MergeExecutor`1.Execute[TKey](PartitionedStream`2 partitions, Boolean ignoreOutput, ParallelMergeOptions options, TaskScheduler taskScheduler, Boolean isOrdered, CancellationState cancellationState, Int32 queryId)
       at System.Linq.Parallel.PartitionedStreamMerger`1.Receive[TKey](PartitionedStream`2 partitionedStream)
       at System.Linq.Parallel.SelectQueryOperator`2.WrapPartitionedStream[TKey](PartitionedStream`2 inputStream, IPartitionedStreamRecipient`1 recipient, Boolean preferStriping, QuerySettings settings)
       at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive[TKey](PartitionedStream`2 inputStream)
       at System.Linq.Parallel.SelectQueryOperator`2.WrapPartitionedStream[TKey](PartitionedStream`2 inputStream, IPartitionedStreamRecipient`1 recipient, Boolean preferStriping, QuerySettings settings)
       at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive[TKey](PartitionedStream`2 inputStream)
       at System.Linq.Parallel.ScanQueryOperator`1.ScanEnumerableQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
       at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
       at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
       at System.Linq.Parallel.QueryOperator`1.GetOpenedEnumerator(Nullable`1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings)
       at System.Linq.Parallel.QueryOpeningEnumerator`1.OpenQuery()
       at System.Linq.Parallel.QueryOpeningEnumerator`1.MoveNext()
       at System.Linq.ParallelEnumerable.ToList[TSource](ParallelQuery`1 source)
       at LoadingImages.Form1..ctor() in D:\C-Sharp\LoadingImages\LoadingImages\LoadingImages\Form1.cs:line 29
       at LoadingImages.Program.Main() in D:\C-Sharp\LoadingImages\LoadingImages\LoadingImages\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2147024809
       Message=Parameter is not valid.
       Source=System.Drawing
       StackTrace:
            at System.Drawing.Bitmap..ctor(String filename)
            at LoadingImages.Form1.<>c.<.ctor>b__6_0(String path) in D:\C-Sharp\LoadingImages\LoadingImages\LoadingImages\Form1.cs:line 31
            at System.Linq.Parallel.SelectQueryOperator`2.SelectQueryOperatorEnumerator`1.MoveNext(TOutput& currentElement, TKey& currentKey)
            at System.Linq.Parallel.SelectQueryOperator`2.SelectQueryOperatorEnumerator`1.MoveNext(TOutput& currentElement, TKey& currentKey)
            at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork()
            at System.Linq.Parallel.SpoolingTaskBase.Work()
            at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
            at System.Linq.Parallel.QueryTask.<>c.<.cctor>b__10_0(Object o)
            at System.Threading.Tasks.Task.InnerInvoke()
            at System.Threading.Tasks.Task.Execute()
       InnerException:

不确定为什么会发生以及如何解决它。

2 个答案:

答案 0 :(得分:2)

我已尝试使用您的代码+模拟调整大小的几个场景:

1)取了700个随机位图 - 工作正常

2)添加了一个非常大的位图(12K x 12K) - 工作正常

3)添加了假位图(某些文本文件重命名为.bmp) - 失败并显示错误

为了找出实际给出错误的内容,可以使用以下代码:

public static Bitmap ResizeImage(Bitmap bmp, int width, int height)
{
    return bmp;
}

static void Main(string[] args)
{
    var imageslist = Directory.EnumerateFiles("C:\\BmpTest", "*.bmp", SearchOption.AllDirectories)
        .AsParallel()
        .Select(path =>
            {
                Bitmap ret = null;
                try
                {
                    ret = new Bitmap(path);
                }
                catch (Exception exc)
                {
                     // put breakpoint here and check path
                }
                return ret;
            })
        .Select(bmp => ResizeImage(bmp, 100, 100))
        .ToList();

答案 1 :(得分:-1)

问题似乎是你调用的ResizeImage方法。也许它不是线程安全的。您应该检查您对此方法的实现,或者您可以与我们分享方法的实现。

ps:我无法评论为什么我必须写作答案。