线程安全的ReferenceEquals

时间:2015-02-19 13:33:48

标签: c# excel

我尝试创建一个VSTO Addin。在此我将Listheet对象存储在列表中。对于我的Addin,使用延迟函数调用在自己的Thread中执行它是很重要的。所以,当我打电话给TestClass.run()时,我在我的工作表列表中进行了2次,首先是在调用延迟函数之前,然后是在延迟函数中的第二次。第二个调用与工作表实例不匹配。我怎样才能做到这一点?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Timers;

namespace Ventron.VRange
{
    public class TestClass
    {
        private static List<OuterWorksheet> sheetList = new List<OuterWorksheet>();

        public static void run(Range range)
        {
            TestClass.sheetList.Add(new OuterWorksheet(range.Worksheet));
            TestClass.getWorkSheet(range.Worksheet);

            ElapsedEventHandler delayedFn = delegate(object sender, ElapsedEventArgs e)
            {
                System.Timers.Timer theTimer = (System.Timers.Timer)sender;
                if (theTimer.Enabled)
                {
                    theTimer.Stop();
                    theTimer.Enabled = false;
                    theTimer.Dispose();
                    theTimer = null;
                    TestClass.getWorkSheet(range.Worksheet);
                }
            };

            System.Timers.Timer timerInstance = new System.Timers.Timer(1);
            timerInstance.Elapsed += new System.Timers.ElapsedEventHandler(delayedFn);
            timerInstance.Interval = 1;
            timerInstance.Enabled = true;
        }

        internal static OuterWorksheet getWorkSheet(Worksheet worksheet)
        {
            System.Diagnostics.Debug.Write("*****************************\n");
            System.Diagnostics.Debug.Write(worksheet.CodeName + "\n");

            foreach (OuterWorksheet outerWS in TestClass.sheetList)
            {
                System.Diagnostics.Debug.Write(outerWS.worksheet.CodeName + "\n");
                if (outerWS.worksheet.Equals(worksheet))
                {
                    System.Diagnostics.Debug.Write("Worksheets are equal\n");
                    return outerWS;
                } else
                    System.Diagnostics.Debug.Write("Worksheets are not equal\n");
            }
            return null;
        }

        internal class OuterWorksheet
        {
            public Worksheet worksheet { get; private set; }
            public OuterWorksheet(Worksheet worksheet)
            {
                this.worksheet = worksheet;
            }
        }
    }
}

输出是:

*****************************
Sheet5
Sheet5
Worksheets are equal

*****************************
Sheet5
Sheet5
Worksheets are not equal

THX!

1 个答案:

答案 0 :(得分:2)

每次获取工作表时,它都会在excel公开的COM对象周围生成一个新的包装器实例,因此它们永远不会被引用相等。 Excel需要唯一的工作表名称,因此只需在检查相等性时比较名称。