第一种就是 最常见的 用Try..Catch..

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;

namespace HustCAD.IntePLM.Win.BatchEnterWinUI
{
    public class SighExcel
    {
        #region DllImport Methods
        [System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        #endregion

        Microsoft.Office.Interop.Excel.ApplicationClass application = null;
        Microsoft.Office.Interop.Excel.Workbook workBook = null;
        Microsoft.Office.Interop.Excel.Worksheet wSheet = null;

        /// <summary>
        /// 对EXCEL指定单元格进行操作
        /// </summary>
        /// <param name="filePath">EXCEL表格所在路径</param>
        /// <param name="row">行号</param>
        /// <param name="column">列号</param>
        /// <param name="code">内容</param>
        /// <returns></returns>
        public bool signExcel(string filePath, int row, int column, string code)
        {
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            object missing = Type.Missing;
            try
            {
                try
                {
                    application = new Microsoft.Office.Interop.Excel.ApplicationClass();
                }
                catch (Exception e)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }
                if (application == null)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }

                application.AlertBeforeOverwriting = false;
                application.AskToUpdateLinks = false;
                application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
                application.DisplayAlerts = false;

                workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
                        true, missing, missing, missing, missing, missing, missing, missing, missing);
                workBook.CheckCompatibility = false;//兼容性检查
                workBook.DoNotPromptForConvert = true;

                wSheet = (Worksheet)workBook.Worksheets[1];
                wSheet.Cells[row, column] = code;
                Microsoft.Office.Interop.Excel.Range rtemp = wSheet.get_Range(wSheet.Cells[3, 4], wSheet.Cells[3, 6]);
                rtemp.Font.Name = "宋体";
                rtemp.Font.Size = 12;
                object RouteWorkbook = false;
                object SaveChanges = XlSaveAction.xlSaveChanges;
                //wBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                workBook.Save();
                workBook.Close(SaveChanges, filePath, RouteWorkbook);
                return true;
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                return false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    KillSpecialExcel(application);
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// Kill Special Excel Process
        /// </summary>
        public static void KillSpecialExcel(Application m_objExcel)
        {
            try
            {
                if (m_objExcel != null)
                {
                    int lpdwProcessId;
                    GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId);
                    System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
                }
            }
            catch (Exception)
            {}
        }

        public string getCellValue(string filePath, int row, int column)
        {
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            object missing = Type.Missing;
            try
            {
                try
                {
                    application = new Microsoft.Office.Interop.Excel.ApplicationClass();
                }
                catch (Exception e)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }
                if (application == null)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }

                application.AlertBeforeOverwriting = false;
                application.AskToUpdateLinks = false;
                application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
                application.DisplayAlerts = false;

                workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
                        true, missing, missing, missing, missing, missing, missing, missing, missing);
                workBook.CheckCompatibility = false;//兼容性检查
                workBook.DoNotPromptForConvert = true;

                wSheet = (Worksheet)workBook.Worksheets[1];
                return ((Microsoft.Office.Interop.Excel.Range)wSheet.Cells[row, column]).Text.ToString().Trim();
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                return "";
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    KillSpecialExcel(application);
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// 得到当前程序的路径
        /// </summary>
        /// <returns></returns>
        static public string GetCurrentPath()
        {
            string asstring = Assembly.GetExecutingAssembly().Location;
            string[] aa = asstring.Split('\\');
            string path = string.Empty;
            foreach (string var in aa)
            {
                if (var != aa[aa.Length - 1])
                    path += var + @"\";
            }
            return path;
        }
    }
}

不会造成循环引用的block

再try中强转你要确认的string 类型

  

大部分GCD方法

1 dispatch_async(dispatch_get_main_queue(), ^{
2     [self doSomething];
3 });

因为self并没有对GCD的block进行持有,没有形成循环引用。目前我还没碰到使用GCD导致循环引用的场景,如果某种场景self对GCD的block进行了持有,则才有可能造成循环引用。

 

成功就是int  catch 就不是 

block并不是属性值,而是临时变量

 1 - (void)doSomething {
 2     [self testWithBlock:^{
 3         [self test];
 4     }];
 5 }
 6 
 7 - (void)testWithBlock:(void(^)())block {
 8     block();
 9 }
10 
11 - (void)test {
12     NSLog(@"test");
13 }

这里因为block只是一个临时变量,self并没有对其持有,所以没有造成循环引用

 

            string a = "avdfd";
            try
            {
                int b = int.Parse(a);
            }
            catch (Exception)
            {
                Console.WriteLine("不是");
            }

block使用对象被提前释放

有这种情况,如果不只是ClassA持有了myBlock,ClassB也持有了myBlock。

图片 1

当ClassA被someObj对象释放后

图片 2

此时,ClassA对象已经被释放,而myBlock还是被ClassB持有,没有释放;如果myBlock这个时被调度,而此时ClassA已经被释放,此时访问的ClassA将是一个nil对象(使用__weak修饰,对象释放时会置为nil),而引发错误。

 

另一个常见错误使用是,开发者担心循环引用错误(如上所述不会出现循环引用的情况),使用__weak。比如

1 __weak typeof(self) weakSelf = self;
2 dispatch_async(dispatch_get_main_queue(), ^{
3     [weakSelf doSomething];
4 });

因为将block作为参数传给dispatch_async时,系统会将block拷贝到堆上,而且block会持有block中用到的对象,因为dispatch_async并不知道block中对象会在什么时候被释放,为了确保系统调度执行block中的任务时其对象没有被意外释放掉,dispatch_async必须自己retain一次对象(即self),任务完成后再release对象(即self)。但这里使用__weak,使dispatch_async没有增加self的引用计数,这使得在系统在调度执行block之前,self可能已被销毁,但系统并不知道这个情况,导致block执行时访问已经被释放的self,而达不到预期的结果。

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注