开发者

Change in behaviour & generation of nullreference exception

开发者 https://www.devze.com 2022-12-22 16:11 出处:网络
I made this program 2hr ago and it ran quit well when i confronted this to presaved .xls file. But when i closed that and started new instance,it started generating null refrence exception why??plz ex

I made this program 2hr ago and it ran quit well when i confronted this to presaved .xls file. But when i closed that and started new instance,it started generating null refrence exception why??plz explain.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;




using System.IO;

using System.Threading;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;


namespace svchost
{

    class MainClass
    {
        Excel.Application oExcelApp;


        static void Main(string[] args)
        {
            MainClass mc = new MainClass();
            while (true)
            {
                if (mc.chec())
                {
                    Console.WriteLine("RUNNING");

                    Thread.Sleep(4000);
                }
                else
                {
                    Console.WriteLine("NOT RUNNING");

                    Thread.Sleep(8000);
                }

            }


        }
        public bool chec()
        {



            try
            {
                oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
                Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook;

                //****PROBLEM FROM HERE*********

            Console.WriteLine(xlwkbook.Name + "\n");
            ke kw = new ke(ref oExcelApp,ref xlwkbook);

            Console.WriteLine(xlwkbook.Author);

            xlwkbook = null;
        }
        catch (Exception ec)
        {
            oExcelApp = null;
            System.GC.Collect();
            Console.WriteLine(ec);
            return false;

        }
        oExcelApp = null;

        System.GC.Collect();
        return true;
    }
}
开发者_如何学Go



class ke

{
    public ke(ref Excel.Application a1, ref Excel.Workbook b1)
    {
        Excel.Worksheet ws = (Excel.Worksheet)a1.ActiveSheet;
        Console.WriteLine(a1.ActiveWorkbook.Name + "\n" + ws.Name);
        Excel.Range rn;
        rn = ws.Cells.Find("657/07", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
   Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);
        Console.WriteLine(rn.Text);

    }

}

}


Wow, a lot of scary things going on in there.

  1. Don't ever write the line GC.Collect() unless you have an extremely good reason. This is not one of those times.

  2. The line oExcelApp = null accomplishes nothing. I'm guessing this was "translated" from a VB script/app where you had to write Set xxx = Nothing, and then the discovery came that the GC is nondeterministic and that you could "fix" it with GC.Collect(). Let the GC do its job, don't mess with it if you don't know what you're doing.

  3. Catching the top-level Exception and eating it... not re-throwing, not wrapping, not logging, nothing. In this case it should probably be a finally, with the return true inside the try block and return false after the finally block.

  4. ref parameters in a method that doesn't need reference semantics for any reason. Get rid of them.

  5. Meaningless class and method names. How are we supposed to understand what's going on here?

  6. Never checking for null results, and this is undoubtedly why you're getting the exception. I see several instances. The first is after the line starting with rn = ws.Cells.Find - this method can return null. The ActiveWorkbook property can also return null, and you pass this to the ke constructor which does not verify that the workbook is a valid reference. Finally, Marshal.GetActiveObject can also return null and you never check to make sure that it succeeds.

  7. Creating a class and using its constructor to do the same work that could be done in a single method. I don't understand why the ke class even exists - it has no methods or properties!. Give the method a proper name, remove that ke class and put it inside the same class that's doing the rest of the work.

  8. Declaring variables and then assigning them on the next line. I suppose this is more of a code style issue but again makes me think that this was some sort of automated translation from VB. If you are assigning to variables immediately after declaring them, then put the declaration and assignment on the same line, Range rn = ....

  9. Usage of Thread.Sleep, presumably to prevent some sort of race condition - and not a reliable means of doing so.

Hopefully one of those things (probably #6) will lead you to a solution...


     public bool chec()
            {
                Excel.Application oExcelApp;


                try
                {

                    oExcelApp = (Excel.

Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); ;
                if (oExcelApp.ActiveWorkbook != null)
                {
                    Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook;


                    ke k = new ke(ref oExcelApp, ref xlwkbook);

                }


            }
            catch 
            {
                if (reg > 100) { } else { reg++; goto End; }//public static int reg=0;
                oExcelApp = null;

                /*Process[] ppo = Process.GetProcessesByName("EXCEL");
                foreach(Process pppp in ppo)
                {
                  pppp.Kill();
                }*/

                End:
                return false;

            }

               finally{ oExcelApp = null;
                System.GC.Collect();}




            return true;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号