如何在C#中处理ObjectDisposedException? [英] How to handle ObjectDisposedException in C#?

查看:180
本文介绍了如何在C#中处理ObjectDisposedException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用"Minitab 17"我的C#应用​​程序中的COM组件.我的应用程序突然崩溃,出现未处理System.ObjectDisposedException".错误信息.我无法确定确切的根本原因,但是我观察到 如果我不使用COM组件,则看不到错误.

堆栈调用跟踪显示此错误消息:

未处理System.ObjectDisposedException
  HResult = -2146232798
  Message =安全手柄已关闭
 来源= mscorlib
  ObjectName =""
  StackTrace:
        at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
        at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle,布尔值&成功)
        at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(SafeFileHandle hFile,NativeOverlapped * lpOverlapped,Int32& lpNumberOfBytesTransferred,布尔值bWait)
        at System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent()
        at System.Threading.ThreadHelper.ThreadStart_Context(对象状态)
        at System.Threading.ExecutionContext.RunInternal(ExecutionContext executeContext,ContextCallback回调,对象状态,布尔值saveSyncCtx)
        at System.Threading.ExecutionContext.Run(ExecutionContext executeContext,ContextCallback回调,对象状态,布尔值saveSyncCtx)
        at System.Threading.ExecutionContext.Run(ExecutionContext executeContext,ContextCallback回调,对象状态)
        at System.Threading.ThreadHelper.ThreadStart()


我在WPF项目中有名为"AutomationProject"的"ReportWindow.xaml"文件;它包含一个按钮,并带有"click"动作:

   点击
    {
    int x = Convert.ToInt32(cmbx.SelectedValue);
    int y = Convert.ToInt32(cmby.SelectedValue);           
   字符串验证msg = validation();
   如果(string.IsNullOrEmpty(validationmsg))
    {
                  
   如果x!= 0&& y!= 0)
    {
      CompatibilityID = DataLayer.GetCompatibiltyTestI(x,y);
      CTDocumentWriter.WriteReportDoc(CompatibilityID);->此处CTDocumentWriter是来自项目名称"Compatibility"的类,如下图所示.
       
    }
    }
    

   公共静态无效WriteReportDoc(int nCompatibilityTestId)
        {
                       
            Utility.MiniTab.CreateMiniTabInstance();此处Utility.MiniTab是来自项目名称"Utility"的类,如下图所示

               字典< string,string> dic = new Dictionary< string,string>();
                dicToleranceInt.Add("a","a1");
                dicToleranceInt.Add("b","b1");

                foreach(dic中的KeyValuePair< string,string>条目)
                {
                   位图tol =
                    Utility.MiniTab.GetToleranceIntervalPlot(nCompatibilityTestId,entry.Value);
                    Image [] insertImgs = {tol_IntervalPlot};
                    string []标签= {entry.Key};
                    Int64 [] imgWidth = {7000000L};
                    Int64 [] imgHeight = {7000000L};
                    SearchAndReplacer.InsertImageToDoc(sPath,insertImgs,标签,imgWidth,imgHeight);
                }

                Utility.MiniTab.Dispose();

        }   

       }

Minitab.cs`类是:

   公共课程MiniTab
    {
       私有静态Mtb.Application MtbApp = null;
       私有静态Mtb.Project MtbProject = null;
       私有静态Mtb.Worksheet MtbWorksheet = null;

       公共静态无效CreateMiniTabInstance()
        {
           如果(MtbApp == null)
            {
                MtbApp =新的Mtb.Application();
                MtbProject = MtbApp.ActiveProject;
                MtbWorksheet = MtbProject.ActiveWorksheet;
                MtbApp.UserInterface.Visible = false;
                MtbApp.UserInterface.DisplayAlerts = false;
            }
        }

       公共静态字符串P_Value {set;得到; }

       私有静态图像MiniTabCommandExecution(字符串命令,布尔IsGraphCmd,DataAccessLayer.Constants.MinitabCommandType cmdType)
        {
           图片graphImage = null;
           试试
            {

                MtbProject.ExecuteCommand(command);
               如果(IsGraphCmd)
                {
                    for(int i = 1; i< = MtbProject.Commands.Count; i ++)
                    {
                        for(int j = 1; j< = MtbProject.Commands.Item(i).Outputs.Count; j ++)
                        {
                           如果(MtbProject.Commands.Item(i).Outputs.Item(j).OutputType == Mtb.MtbOutputTypes.OTGraph)
                            {
                                MtbProject.Commands.Item(i).Outputs.Item(j).Graph.CopyToClipboard();
                                graphImage = System.Windows.Forms.Clipboard.GetImage();
                                //  System.Windows.Forms.Clipboard.Clear();
                            }
                        }
                    }
                   如果(cmdType == DataAccessLayer.Constants.MinitabCommandType.NormalProbability)
                    {
                        if(MtbWorksheet.Columns!= null&& MtbWorksheet.Columns.Item(5)!= null&& MtbWorksheet.Columns.Item(5).GetData(1,1)!= null)
                            P_Value = MtbWorksheet.Columns.Item(5).GetData(1,1);
                    }

                }

               同时(MtbProject.Commands.Count> 0)
                {
                    MtbProject.Commands.Remove(1);
                }
            }
            
            catch(异常例外)
            {
                MessageBox.Show(ex.Message.ToString());
            }
          
           返回graphImage;
        }

       公共静态无效Dispose()
        {
            MtbApp.Quit();
            System.Diagnostics.Process [] proc = System.Diagnostics.Process.GetProcessesByName("Mtb");
            proc [0] .Kill();
            
        }

       公共静态无效ExportDt(DataTable dt)
        {
           试试
            {
                //Stream myStream;
                //SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                //saveFileDialog1.Filter ="Excel Workbook | * .csv";    //|(*.xls);//* .txt |所有文件(*.*)| *.*";
                //saveFileDialog1.FilterIndex = 2;
                //saveFileDialog1.RestoreDirectory = true;

                //if(saveFileDialog1.ShowDialog()== DialogResult.OK)
                //{
                //    if((mystream = saveFileDialog1.OpenFile())!= null)
                {
                    //编写流的代码在这里.
                    //字符串路径= saveFileDialog1.FileName;
                   字符串路径= ConfigurationManager.AppSettings ["DataSheetVMinMax"].ToString();
                   如果(File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    //myStream.Close();
                   如果(dt.Rows.Count> 0)
                    {
                        //string pathTosaveCsv = Microsoft.ApplicationBlocks.ConfigurationManagement.ConfigurationManager.PathtoSaveCSV;
                        //string path = pathTosaveCsv +"UnpaidClaims.csv";
                       字符串strValue = string.Empty;
                        for(int i = 0; i< dt.Columns.Count; i ++)
                        {
                           如果(!string.IsNullOrEmpty(strValue))
                            {
                                strValue = strValue +," + dt.Columns [i] .ToString();
                            }
                           其他
                            {
                                strValue = dt.Columns [i] .ToString();
                            }
                        }
                        strValue = strValue + Environment.NewLine;

                        for(int i = 0; i< dt.Rows.Count; i ++)
                        {
                            for(int j = 0; j< dt.Columns.Count; j ++)
                            {
                               如果(j> 0)
                                {
                                    strValue = strValue +," + dt.Rows [i] [j] .ToString().Replace(,",;"));
                                }
                               其他
                                {
                                    strValue = strValue + dt.Rows [i] [j] .ToString().Replace(,",";;");
                                }
                            }
                            strValue = strValue + Environment.NewLine;
                        }
                        System.IO.File.WriteAllText(path,strValue);
                    }
                }
              
            }
            catch(objex异常)
            {
               抛出objex;
            }
        }

      
       公共静态字符串GetCommand(DataAccessLayer.Constants.MinitabCommandType cmdType,字符串columnName,字符串标题,DoseAccuracyGraphData graphData)
        {
           字符串命令= string.Empty;
            StringBuilder sb = new StringBuilder();
           试试
            {
               开关(cmdType)
                {
                   案例DataAccessLayer.Constants.MinitabCommandType.ToleranceInterval:

                        sb.Append("TolInterval'");
                        sb.Append(columnName);
                        sb.Append('; GTIPlot; Confidence 95.0; PPercent 97.5.");
                       休息;

                   案例DataAccessLayer.Constants.MinitabCommandType.Histogram:

                        sb.Append("Histogram'");
                        sb.Append(columnName);
                        sb.Append('';参考1");
                        sb.Append(graphData.UL_Lab);
                        sb.Append(颜色74;尺寸3;角度90;  TCOLOR 74;");//颜色74是蓝色
                        sb.Append(参考1");
                        sb.Append(graphData.LL_Lab);
                        sb.Append("Color 74;  Size 3; Angle 90;  TCOLOR 74;");
                        sb.Append(参考1");
                        sb.Append(graphData.Target);
                        sb.Append("Color 25;  Size 3; Angle 90;  TCOLOR 25;");//Color 25是红色
                        sb.Append(参考1");
                        sb.Append(graphData.LL_Protocal);
                        sb.Append("Color 50;  Size 3; Angle 90;  TCOLOR 50;");//Color 50为绿色
                        sb.Append(参考1");
                        sb.Append(graphData.UL_Protocal);
                        sb.Append("Color 50;  Size 3; Angle 90;  TCOLOR 50;  Title \");//Color 50是绿色
                        sb.Append(title);
                        sb.Append("tolerance Interval Plot for");
                        sb.Append(columnName);
                        sb.Append("\";  SubTitle \"95%Tolerance Interval \"; SubTitle \"Aestast 97.5%                        休息;
                   案例DataAccessLayer.Constants.MinitabCommandType.NormalProbability:
                        sb.Append("NormTest'");
                        sb.Append(columnName);
                        sb.Append(';标题\" \;  SPVALUE C5.");
                       休息;

                }
                command = sb.ToString();
            }
            catch(异常例外)
            {
            }
           返回命令;
        }

       公共静态位图裁剪(位图位图,矩形rect)
        {
           位图roppedBitmap = null;
           试试
            {
                //创建具有所需大小和相同像素格式的新位图
                croppedBitmap =新的Bitmap(rect.Width,rect.Height,bitmap.PixelFormat);

                //创建图形包装器"画入我们的新位图
                //使用";保证调用gfx.Dispose()
               使用(Graphics gfx = Graphics.FromImage(croppedBitmap))
                {
                    //将原始位图的所需部分绘制到新的位图中
                    gfx.DrawImage(bitmap,0,0,rect,GraphicsUnit.Pixel);
                }
            }
            catch(异常例外)
            {
            }

           返回croppedBitmap;
        }

       公共静态位图GetToleranceIntervalPlot(int nCompatibilityTestId,字符串Vmin_or_Vmax,BussinessEntity.ReportEditFields objReportEditFileds)
        {
           位图groupImage = null;
           试试
            {


               字符串OpenCsvFileCommand ="Wopen" +"\" + ConfigurationManager.AppSettings ["DataSheetVMinMax"].ToString()+"\" +&;; FType; CSV; DecSep;时期;场地;逗号; TDelimiter; DoubleQuote.";

                MiniTabCommandExecution(OpenCsvFileCommand,false,0);

                //正态概率图
               字符串normalTest_Cmd = GetCommand(Constants.MinitabCommandType.NormalProbability,Vmin_or_Vmax," ;, null);
                //执行命令并获取pvalue来确定参数还是非参数
               图片normalTest = MiniTabCommandExecution(normalTest_Cmd,true,Constants.MinitabCommandType.NormalProbability);
               双pvalue;
               如果(P_Value.ToString().Contains("<)))
                    pvalue = Convert.ToDouble(P_Value.Replace('<','').Trim());
               其他
                    pvalue = Convert.ToDouble(P_Value);
                //公差区间图
               字符串tolInt_Cmd =
                          GetCommand(Constants.MinitabCommandType.ToleranceInterval,Vmin_or_Vmax," ;, null);
                //执行命令并获得公差  intval  plot
               图片imgTolInt =
                MiniTabCommandExecution(tolInt_Cmd,true,Constants.MinitabCommandType.ToleranceInterval);

               如果(imgTolInt!= null)
                {
                    ////裁剪上面的公差区间图像以单独获取区间图
                   位图roppedIntervalPlot =裁剪(新位图(imgTolInt),新矩形(20、160、430、90));

                   位图cropTable;
                   字符串ToleranceType = string.Empty;
                   如果(pvalue> 0.05)
                    {
                        ToleranceType =正常";
                        cropTable = Crop(新的Bitmap(imgTolInt),新的Rectangle(460、128、110、49));
                    }
                   其他
                    {
                        ToleranceType =非参数";
                        cropTable = Crop(新的Bitmap(imgTolInt),新的Rectangle(460、178、110、49));
                    }


                    ////直方图
                   字符串histogram_Cmd = GetCommand(Constants.MinitabCommandType.Histogram,Vmin_or_Vmax,ToleranceType,VminRefLinesData);
                    ////执行命令并获取直方图图
                   图片img直方图=
                    MiniTabCommandExecution(histogram_Cmd,true,Constants.MinitabCommandType.Histogram);

                    Image [] imageNames = {imgHistogram,croppedIntervalPlot,cropTable,normalTest};
                    groupImage =新的位图(800,1250);
                   使用(Graphics g = Graphics.FromImage(groupImage))
                    {
                        System.Drawing.Color color = ColorTranslator.FromHtml(#E5E5E5");
                        g.清除(颜色);
                        for(int i = 0; i< imageNames.Count(); i ++)
                        {
                            System.Drawing.Size newSize =新System.Drawing.Size((int)(imageNames [i] .Width * 1.4),(int)(imageNames [i] .Height * 1.4));
                           使用(位图img =新位图(imageNames [i],newSize))
                            {
                               开关(i)
                                {
                                    //直方图图
                                   案例0:
                                        g.DrawImage(img,新的System.Drawing.Point(0,0));
                                       休息;
                                    //间隔图
                                   情况1:
                                        System.Drawing.Size newSize1 =新System.Drawing.Size((int)(imageNames [i] .Width * 1.4),(int)(imageNames [i] .Height * 1.8));
                                       使用(位图img1 =新位图(imageNames [i],newSize1))
                                        {
                                            g.DrawImage(img1,新的System.Drawing.Point(0,540));
                                        }
                                       休息;
                                    //统计表(普通或非参数)
                                   情况2:
                                        g.DrawImage(img,新的System.Drawing.Point(600,570));
                                       休息;
                                    //正态概率图
                                   情况3:
                                        g.DrawImage(img,新的System.Drawing.Point(0,720));
                                       休息;
                                   默认值:
                                       休息;
                                }
                            }
                        }
                    }
                }

            }
            catch(异常例外)
            {
               扔前;
            }
           终于
            {
               
            }
           返回groupImage;
        }
    }


Padma Yeddula

I am using the "Minitab 17" COM component in my C# application. My application suddenly crashes with "System.ObjectDisposedException was unhandled" error message.  I am unable to identify exact root cause, but I have observed that if I don't use the COM component, I don't see the error.

The stack call trace is showing this error messsage:

System.ObjectDisposedException was unhandled
  HResult=-2146232798
  Message=Safe handle has been closed
  Source=mscorlib
  ObjectName=""
  StackTrace:
       at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
       at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
       at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(SafeFileHandle hFile, NativeOverlapped* lpOverlapped, Int32& lpNumberOfBytesTransferred, Boolean bWait)
       at System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent()
       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()


I have `ReportWindow.xaml` file in WPF Project of name "AutomationProject"; it contains one button, with this `click` action:

    click
    {
    int x= Convert.ToInt32(cmbx.SelectedValue);
    int y= Convert.ToInt32(cmby.SelectedValue);           
    string validationmsg = validation();
    if (string.IsNullOrEmpty(validationmsg))
    {
                  
    if x!= 0 && y!= 0)
    {
     CompatibilityID = DataLayer.GetCompatibiltyTestI(x,y);
     CTDocumentWriter.WriteReportDoc(CompatibilityID);->Here CTDocumentWriter is a class from project name "Compatibility" as shown below.
       
    }
    }
    

    public static void WriteReportDoc(int nCompatibilityTestId)
        {
                       
           Utility.MiniTab.CreateMiniTabInstance();Here Utility.MiniTab is a class from project name "Utility" as shown below

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dicToleranceInt.Add("a", "a1");
                dicToleranceInt.Add("b", "b1");

                foreach (KeyValuePair<string, string> entry in dic)
                {
                    Bitmap tol =
                    Utility.MiniTab.GetToleranceIntervalPlot(nCompatibilityTestId, entry.Value);
                    Image[] insertImgs = { tol_IntervalPlot };
                    string[] tags = { entry.Key };
                    Int64[] imgWidth = { 7000000L };
                    Int64[] imgHeight = { 7000000L };
                    SearchAndReplacer.InsertImageToDoc(sPath, insertImgs, tags, imgWidth, imgHeight);
                }

               Utility.MiniTab.Dispose();

        }    

       }

`Minitab.cs` class  is:

    public class MiniTab
    {
        private static Mtb.Application MtbApp = null;
        private static Mtb.Project MtbProject = null;
        private static Mtb.Worksheet MtbWorksheet = null;

        public static void CreateMiniTabInstance()
        {
            if (MtbApp == null)
            {
                MtbApp = new Mtb.Application();
                MtbProject = MtbApp.ActiveProject;
                MtbWorksheet = MtbProject.ActiveWorksheet;
                MtbApp.UserInterface.Visible = false;
                MtbApp.UserInterface.DisplayAlerts = false;
            }
        }

        public static string P_Value { set; get; }

        private static Image MiniTabCommandExecution(string command, bool IsGraphCmd, DataAccessLayer.Constants.MinitabCommandType cmdType)
        {
            Image graphImage = null;
            try
            {

                MtbProject.ExecuteCommand(command);
                if (IsGraphCmd)
                {
                    for (int i = 1; i <= MtbProject.Commands.Count; i++)
                    {
                        for (int j = 1; j <= MtbProject.Commands.Item(i).Outputs.Count; j++)
                        {
                            if (MtbProject.Commands.Item(i).Outputs.Item(j).OutputType == Mtb.MtbOutputTypes.OTGraph)
                            {
                                MtbProject.Commands.Item(i).Outputs.Item(j).Graph.CopyToClipboard();
                                graphImage = System.Windows.Forms.Clipboard.GetImage();
                                //  System.Windows.Forms.Clipboard.Clear();
                            }
                        }
                    }
                    if (cmdType == DataAccessLayer.Constants.MinitabCommandType.NormalProbability)
                    {
                        if (MtbWorksheet.Columns != null && MtbWorksheet.Columns.Item(5) != null && MtbWorksheet.Columns.Item(5).GetData(1, 1) != null)
                            P_Value = MtbWorksheet.Columns.Item(5).GetData(1, 1);
                    }

                }

                while (MtbProject.Commands.Count > 0)
                {
                    MtbProject.Commands.Remove(1);
                }
            }
            
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
          
            return graphImage;
        }

        public static void Dispose()
        {
            MtbApp.Quit();
            System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("Mtb");
           proc[0].Kill();
            
        }

        public static void ExportDt(DataTable dt)
        {
            try
            {
                //Stream myStream;
                //SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                //saveFileDialog1.Filter = "Excel Workbook|*.csv";    //|(*.xls)";// *.txt|All files (*.*)|*.*";
                //saveFileDialog1.FilterIndex = 2;
                //saveFileDialog1.RestoreDirectory = true;

                //if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                //{
                //    if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    // Code to write the stream goes here.
                    // string path = saveFileDialog1.FileName;
                    string path = ConfigurationManager.AppSettings["DataSheetVMinMax"].ToString();
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    //myStream.Close();
                    if (dt.Rows.Count > 0)
                    {
                        //string pathTosaveCsv = Microsoft.ApplicationBlocks.ConfigurationManagement.ConfigurationManager.PathtoSaveCSV;
                        //string path = pathTosaveCsv + "UnpaidClaims.csv";
                        string strValue = string.Empty;
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(strValue))
                            {
                                strValue = strValue + "," + dt.Columns[i].ToString();
                            }
                            else
                            {
                                strValue = dt.Columns[i].ToString();
                            }
                        }
                        strValue = strValue + Environment.NewLine;

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            for (int j = 0; j < dt.Columns.Count; j++)
                            {
                                if (j > 0)
                                {
                                    strValue = strValue + "," + dt.Rows[i][j].ToString().Replace(",", ";");
                                }
                                else
                                {
                                    strValue = strValue + dt.Rows[i][j].ToString().Replace(",", ";");
                                }
                            }
                            strValue = strValue + Environment.NewLine;
                        }
                        System.IO.File.WriteAllText(path, strValue);
                    }
                }
              
            }
            catch (Exception objex)
            {
                throw objex;
            }
        }

      
        public static string GetCommand(DataAccessLayer.Constants.MinitabCommandType cmdType, string columnName, string title, DoseAccuracyGraphData graphData)
        {
            string command = string.Empty;
            StringBuilder sb = new StringBuilder();
            try
            {
                switch (cmdType)
                {
                    case DataAccessLayer.Constants.MinitabCommandType.ToleranceInterval:

                        sb.Append("TolInterval '");
                        sb.Append(columnName);
                        sb.Append("'; GTIPlot; Confidence 95.0; PPercent 97.5.");
                        break;

                    case DataAccessLayer.Constants.MinitabCommandType.Histogram:

                        sb.Append("Histogram '");
                        sb.Append(columnName);
                        sb.Append("';Reference 1 ");
                        sb.Append(graphData.UL_Lab);
                        sb.Append(";Color 74;  Size 3; Angle 90;  TCOLOR 74;");//Color 74 is blue
                        sb.Append("Reference 1 ");
                        sb.Append(graphData.LL_Lab);
                        sb.Append(";Color 74;  Size 3; Angle 90;  TCOLOR 74;");
                        sb.Append("Reference 1 ");
                        sb.Append(graphData.Target);
                        sb.Append(";Color 25;  Size 3; Angle 90;  TCOLOR 25;");//Color 25 is red
                        sb.Append("Reference 1 ");
                        sb.Append(graphData.LL_Protocal);
                        sb.Append(";Color 50;  Size 3; Angle 90;  TCOLOR 50;");//Color 50 is green
                        sb.Append("Reference 1 ");
                        sb.Append(graphData.UL_Protocal);
                        sb.Append(";Color 50;  Size 3; Angle 90;  TCOLOR 50;  Title \"");//Color 50 is green
                        sb.Append(title);
                        sb.Append(" Tolerance Interval Plot for ");
                        sb.Append(columnName);
                        sb.Append("\";  SubTitle \"95% Tolerance Interval\"; SubTitle \"Atleast 97.5% of population covered\";  Bar.");
                        break;
                    case DataAccessLayer.Constants.MinitabCommandType.NormalProbability:
                        sb.Append("NormTest '");
                        sb.Append(columnName);
                        sb.Append("'; Title \"\";  SPVALUE C5.");
                        break;

                }
                command = sb.ToString();
            }
            catch (Exception ex)
            {
            }
            return command;
        }

        public static Bitmap Crop(Bitmap bitmap, Rectangle rect)
        {
            Bitmap croppedBitmap = null;
            try
            {
                // create new bitmap with desired size and same pixel format
                croppedBitmap = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat);

                // create Graphics "wrapper" to draw into our new bitmap
                // "using" guarantees a call to gfx.Dispose()
                using (Graphics gfx = Graphics.FromImage(croppedBitmap))
                {
                    // draw the wanted part of the original bitmap into the new bitmap
                    gfx.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel);
                }
            }
            catch (Exception ex)
            {
            }

            return croppedBitmap;
        }

        public static Bitmap GetToleranceIntervalPlot(int nCompatibilityTestId, string Vmin_or_Vmax, BussinessEntity.ReportEditFields objReportEditFileds)
        {
            Bitmap groupImage = null;
            try
            {


                string OpenCsvFileCommand = "Wopen " + "\"" + ConfigurationManager.AppSettings["DataSheetVMinMax"].ToString() + "\"" + "; FType; CSV; DecSep; Period; Field; Comma; TDelimiter; DoubleQuote.";

                MiniTabCommandExecution(OpenCsvFileCommand, false, 0);

                //Normal probability graph
                string normalTest_Cmd = GetCommand(Constants.MinitabCommandType.NormalProbability, Vmin_or_Vmax, " ", null);
                //executes command and get the pvalue to decide whether a parametric or non parametric 
                Image normalTest = MiniTabCommandExecution(normalTest_Cmd, true, Constants.MinitabCommandType.NormalProbability);
                double pvalue;
                if (P_Value.ToString().Contains("<"))
                    pvalue = Convert.ToDouble(P_Value.Replace('<', ' ').Trim());
                else
                    pvalue = Convert.ToDouble(P_Value);
                //Tolerance Interval plot 
                string tolInt_Cmd =
                         GetCommand(Constants.MinitabCommandType.ToleranceInterval, Vmin_or_Vmax, " ", null);
                //executes command and get the tolerance  intval  plot
                Image imgTolInt =
                MiniTabCommandExecution(tolInt_Cmd, true, Constants.MinitabCommandType.ToleranceInterval);

                if (imgTolInt != null)
                {
                    ////crop the above toler interval image to get the interval plot alone
                    Bitmap croppedIntervalPlot = Crop(new Bitmap(imgTolInt), new Rectangle(20, 160, 430, 90));

                    Bitmap cropTable;
                    string ToleranceType = string.Empty;
                    if (pvalue > 0.05)
                    {
                        ToleranceType = "Normal";
                        cropTable = Crop(new Bitmap(imgTolInt), new Rectangle(460, 128, 110, 49));
                    }
                    else
                    {
                        ToleranceType = "Non Parametric";
                        cropTable = Crop(new Bitmap(imgTolInt), new Rectangle(460, 178, 110, 49));
                    }


                    ////Histogram plot 
                    string histogram_Cmd = GetCommand(Constants.MinitabCommandType.Histogram, Vmin_or_Vmax, ToleranceType, VminRefLinesData);
                    ////executes command and get histogram plot
                    Image imgHistogram =
                    MiniTabCommandExecution(histogram_Cmd, true, Constants.MinitabCommandType.Histogram);

                    Image[] imageNames = { imgHistogram, croppedIntervalPlot, cropTable, normalTest };
                    groupImage = new Bitmap(800, 1250);
                    using (Graphics g = Graphics.FromImage(groupImage))
                    {
                        System.Drawing.Color colour = ColorTranslator.FromHtml("#E5E5E5");
                        g.Clear(colour);
                        for (int i = 0; i < imageNames.Count(); i++)
                        {
                            System.Drawing.Size newSize = new System.Drawing.Size((int)(imageNames[i].Width * 1.4), (int)(imageNames[i].Height * 1.4));
                            using (Bitmap img = new Bitmap(imageNames[i], newSize))
                            {
                                switch (i)
                                {
                                    //Histogram graph
                                    case 0:
                                        g.DrawImage(img, new System.Drawing.Point(0, 0));
                                        break;
                                    //Interval Plot
                                    case 1:
                                        System.Drawing.Size newSize1 = new System.Drawing.Size((int)(imageNames[i].Width * 1.4), (int)(imageNames[i].Height * 1.8));
                                        using (Bitmap img1 = new Bitmap(imageNames[i], newSize1))
                                        {
                                            g.DrawImage(img1, new System.Drawing.Point(0, 540));
                                        }
                                        break;
                                    //Statistical Table (Normal or Non parametric)
                                    case 2:
                                        g.DrawImage(img, new System.Drawing.Point(600, 570));
                                        break;
                                    //Normal probability plot
                                    case 3:
                                        g.DrawImage(img, new System.Drawing.Point(0, 720));
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
               
            }
            return groupImage;
        }
    }


Padma Yeddula

推荐答案

也许您应该致电 MtbWorksheet.Dispose( ) MiniTab.Dispose()中的MtbProject.Dispose() MtbApp.Dispose().如果没有此类功能,请考虑调用 这些对象的 Marshal.ReleaseComObject Marshal.FinalReleaseComObject .最好按相反的创建顺序进行销毁.

Maybe you should call MtbWorksheet.Dispose(), MtbProject.Dispose() and MtbApp.Dispose() inside MiniTab.Dispose(). If there are no such functions, then consider calling Marshal.ReleaseComObject or Marshal.FinalReleaseComObject for these objects. This destruction is better to do in reverse order of creation.


这篇关于如何在C#中处理ObjectDisposedException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆