错误处理多个异步任务

时间:2013-10-04 19:01:32

标签: c# asynchronous task async-await nullreferenceexception

我收到一个错误,当我有多个异步任务时,我无法弄明白。我不能使用parallel,因为任务必须按照我排队的顺序返回。

当我第二次尝试调用PartProcessor()时,我第二次收到错误。

processedParts = await new PartsProcessor.PartProcessor().ProcessParts(userID, elevations, true);

这有效

    public async static Task<List<Bitmap>> RollUpDrawingsImageTotalsListAsync(Guid userID, IElevation[] elevations)
{
    List<Bitmap> totals = new List<Bitmap>();
    var processedParts = await new PartsProcessor.PartProcessor().ProcessParts(userID, elevations, false);

    processedParts.Elevation = elevations[0];

    totals.Add(await MaterialsList.Manager.GetMaterialListAsync(processedParts).Result.GetDrawingAsync(true));

    totals.Add(await Optimization.Manager.GetOptimizedPartsAsync(processedParts).Result.GetDrawingAsync(true));

    totals.Add(await CutSheet.Manager.GetCutSheet(processedParts).GetDrawingAsync(true));

    return totals;
}

但是当我的方法体看起来如此时,我得到了这个错误:“注意我是如何在totals.Add(等待CutSheet ......”之后添加PartProcessor的。“

    public async static Task<List<Bitmap>> RollUpDrawingsImageTotalsListAsync(Guid userID, IElevation[] elevations)
{
    List<Bitmap> totals = new List<Bitmap>();
    var processedParts = await new PartsProcessor.PartProcessor().ProcessParts(userID, elevations, false);

    processedParts.Elevation = elevations[0];

    totals.Add(await MaterialsList.Manager.GetMaterialListAsync(processedParts).Result.GetDrawingAsync(true));

    totals.Add(await Optimization.Manager.GetOptimizedPartsAsync(processedParts).Result.GetDrawingAsync(true));

    processedParts = await new PartsProcessor.PartProcessor().ProcessParts(userID, elevations, true);
    totals.Add(await CutSheet.Manager.GetCutSheet(processedParts).GetDrawingAsync(true));

    return totals;
}

-----------------------------------------错误----- ------------------------------

    <Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Object reference not set to an instance of an object.
</ExceptionMessage>
<ExceptionType>System.NullReferenceException</ExceptionType>
<StackTrace>
at CutSheet.CutSheet.<GetDrawingAsync>d__0.MoveNext() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\AlumCloud\CutSheet\CutSheet.cs:line 125 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at AlumCloudPlans.Manager.<RollUpDrawingsImageTotalsListAsync>d__33.MoveNext() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\AlumCloud\AlumCloudPlans\PlanManager.cs:line 453 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at AlumCloudPlans.Manager.<RollUpProjectPDFAsync>d__65.MoveNext() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\AlumCloud\AlumCloudPlans\PlanManager.cs:line 583 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at AlumCloud.Controllers.Drawings.RollupController.<Get>d__0.MoveNext() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\AlumCloud\AlumCloud\Controllers\Drawings\RollupController.cs:line 39
</StackTrace>
</Error>

-------------- GetDrawingAsync ------------------------- GetDrawingAsync处理此对象属性并构建位图内容容器。处理完所有属性后,此对象可以具有1-n个位图容器,这些容器在继承的基类中处理。每个位图容器都绘制在一个大位图上。

 public async Task<Bitmap> GetDrawingAsync(bool forTotals = false)
    {

        PartsProcessor.IGroupedParts parts = await this.ProcessedParts.GroupParts(PartsProcessor.GroupOption.CutSheet);

        List<Bitmap> containers = new List<Bitmap>();

        Bitmap resDraw = null;
        int totalHeight = 0,
            outHeight = 0;

        if (parts.Doors != null)
        {
            if (parts.Doors.Count() > 0)
            {
                containers.Add(ContentContainers.GetContentContainer(parts.Doors.ToList(), ContainerType.CutSheet, Resources.Title_Doors, out outHeight));
                totalHeight += outHeight;
            };
        }
        if (parts.Leafs != null)
        {
            if (parts.Leafs.Count() > 0)
            {
                containers.Add(ContentContainers.GetContentContainer(parts.Leafs.ToList(), ContainerType.CutSheet, Resources.Title_Leafs, out outHeight));
                totalHeight += outHeight;
            };
        }

        //....many lines of code ommitted for readablitly

        if (forTotals)
        {
            resDraw = this.DrawPage(
                      ref containers,
                      totalHeight,
                      Resources.Header,
                      this.ProcessedParts.Elevation.ProjectName,
                      "Totals",
                      Resources.Footer
                      );
        }
        else
        {
            resDraw = this.DrawPage(
                            ref containers,
                            totalHeight,
                            Resources.Header,
                            string.Format(Resources.Project, this.Elevation.ProjectName),
                            string.Format(Resources.Elevation, this.Elevation.Name),
                            Resources.Footer
                            );
        };

        return resDraw;
    }

----------------------绘图基类---------------------- ----------------- ..代码ommited

   public abstract class DrawingBase
{

    public Bitmap DrawPage(ref List<Bitmap> containers, int totalHeight, string header, string subHead1, string subHead2, string footer)
    {
        return DrawPageHelper(ref  containers, totalHeight, header, subHead1, subHead2, footer);
    }

    public Bitmap DrawPage(ref List<Bitmap> containers, int totalHeight, string header, string subHead1, string subHead2, string footer, decimal cost)
    {
        return DrawPageHelper(ref  containers, totalHeight, header, subHead1, subHead2, footer, cost);
    }

    Bitmap DrawPageHelper(ref List<Bitmap> containers, int totalHeight, string header, string subHead1, string subHead2, string footer, decimal cost = 0)
    {

        int cnt = containers.Count(),
            prevHeight = 10,
            extra = 0,
            extraHeader = 0;

        if (cost > 0)
        {
            extra = 150;
        }
        else if (header.ToLower().Contains("optimization"))
        {
            extra = 50;
            extraHeader = 50;
        }

        totalHeight = totalHeight + (CONTAINER_SPACE * cnt) + HEADER_HEIGHT + FOOTER_HEIGHT + extra;

        if (totalHeight < DrawingOptions.PAGE_HEIGHT_SIZE)
        {
            totalHeight = DrawingOptions.PAGE_HEIGHT_SIZE;
        }


        var canvas = new Bitmap(DrawingOptions.PAGE_WIDTH_SIZE, totalHeight);
        canvas.SetResolution(150, 150);
        short center = (short)(DrawingOptions.PAGE_WIDTH_SIZE / 2);

        using (var dc = Graphics.FromImage(canvas))
        {
            dc.Clear(BACK_COLOR);
            dc.SmoothingMode = SmoothingMode.HighQuality;

            for (byte i = 0; i < cnt; i++)
            {
                using (var bm = containers[i])
                {
                    dc.DrawImageUnscaled(bm, -1, prevHeight + 5 + HEADER_HEIGHT + extraHeader);

                    prevHeight += containers[i].Height + CONTAINER_SPACE;
                };
            }

            using (var pen = DrawingOptions.GetDetailsPen(PenAlignment.Inset))
            {
                //page edge
                //dc.DrawRectangle(pen, 2, 2, canvas.Width - 4, canvas.Height - 3);

                //header
                string txt;
                System.Drawing.SizeF txtSize;
                using (var brush = new SolidBrush(DrawingOptions.LINE_COLOR))
                using (var sFont = DrawingOptions.GetFont(DrawingOptions.FontSize.Small))
                using (var sLargerFont = DrawingOptions.GetFont(DrawingOptions.FontSize.Small_Larger))
                using (var mFont = DrawingOptions.GetFont(DrawingOptions.FontSize.Medium))
                using (var lFont = DrawingOptions.GetFont(DrawingOptions.FontSize.Large))
                {
                    txt = header;//sheet type. Estimate, Cut, Parts, ect..
                    System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
                    drawFormat.FormatFlags = StringFormatFlags.DirectionVertical;
                    txtSize = dc.MeasureString(txt, sLargerFont);
                    dc.DrawRectangle(pen, new Rectangle(0, -1, (short)txtSize.Height + 1, (byte)txtSize.Width));
                    dc.DrawString(txt, sLargerFont, brush, 0, 1, drawFormat);

                    //
                    txt = subHead1;//project name
                    txtSize = dc.MeasureString(txt, mFont);
                    dc.DrawRectangle(pen, new Rectangle((short)txtSize.Height + 1, -1, (short)txtSize.Width, (byte)txtSize.Height + 1));
                    dc.DrawString(txt, mFont, brush, (short)txtSize.Height + 1, 1);

                    txt = subHead2;//elevation name
                    txtSize = dc.MeasureString(txt, sFont);
                    dc.DrawRectangle(pen, new Rectangle((short)((canvas.Width - txtSize.Width) + 5), -1, (short)txtSize.Width + 55, (byte)txtSize.Height + 1));
                    dc.DrawString(txt, sFont, brush, (canvas.Width - txtSize.Width + 5), 1);
                    //header end

                    //footer
                    txt = footer;
                    txtSize = dc.MeasureString(txt, sLargerFont);
                    dc.DrawLine(pen, 0, canvas.Height - (txtSize.Height + 5), canvas.Width, canvas.Height - (txtSize.Height + 5));
                    dc.DrawString(txt, sLargerFont, brush, (short)(center - (txtSize.Width / 2)), canvas.Height - txtSize.Height - 2);

                    if (cost > 0)
                    {

                        //FOB shipping
                        txt = String.Format("Tax: {0:C}", 0.00m);
                        txtSize = dc.MeasureString(txt, sLargerFont);
                        dc.DrawString(txt, sLargerFont, brush, (short)(canvas.Width - (txtSize.Width + 10)), (canvas.Height - ((txtSize.Height * 3) + 15)) - 50);

                        //FOB shipping
                        txt = String.Format("FOB: {0:C}", 0.00m);
                        txtSize = dc.MeasureString(txt, sLargerFont);
                        dc.DrawString(txt, sLargerFont, brush, (short)(canvas.Width - (txtSize.Width + 10)), (canvas.Height - ((txtSize.Height * 2) + 10)) - 50);

                        //total cost
                        txt = String.Format("Total Cost: {0:C}", cost);
                        txtSize = dc.MeasureString(txt, sLargerFont);
                        dc.DrawString(txt, sLargerFont, brush, (short)(canvas.Width - txtSize.Width), (canvas.Height - txtSize.Height - 2) - 50);

                    }
                }
            }
        }
        return canvas;
    }

我需要做些什么来解决这个错误?

0 个答案:

没有答案