当前位置: 首页>>代码示例>>C#>>正文


C# WeakReference类代码示例

本文整理汇总了C#中WeakReference的典型用法代码示例。如果您正苦于以下问题:C# WeakReference类的具体用法?C# WeakReference怎么用?C# WeakReference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


WeakReference类属于命名空间,在下文中一共展示了WeakReference类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

    public static int Main() {
        CreateArray();

        WeakReference weak = new WeakReference(array);
                
        bool ans1 = weak.IsAlive;
        Console.WriteLine(ans1);

        if(ans1==false) { // GC.Collect() has already occurred..under GCStress
            Console.WriteLine("Test for WeakReference.IsAlive passed!");
            return 100;
        }

        //else, do an expicit collect.
        DestroyArray();
        GC.Collect();
        
        bool ans2 = weak.IsAlive;
        Console.WriteLine(ans2);

        if((ans1 == true) && (ans2==false)) {
            Console.WriteLine("Test for WeakReference.IsAlive passed!");
            return 100;
        }
        else {
            Console.WriteLine("Test for WeakReference.IsAlive failed!");
            return 1;
        }
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:29,代码来源:IsAlive.cs

示例2: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: TrackResurrection will return correct value when construct the WeakReference for an object instance");

        try
        {
            Object obj = new Object();
            WeakReference reference = new WeakReference(obj, true);

            if (!reference.TrackResurrection)
            {
                TestLibrary.TestFramework.LogError("001.1", "TrackResurrection returns false when construct the WeakReference for an object instance");
                retVal = false;
            }

            reference = new WeakReference(obj, false);

            if (reference.TrackResurrection)
            {
                TestLibrary.TestFramework.LogError("001.2", "TrackResurrection returns true when construct the WeakReference for an object instance");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.3", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:l1183479157,项目名称:coreclr,代码行数:34,代码来源:weakreferencetrackresurrection_cti.cs

示例3: MetadataCachingWithGarbageCollectionTemplate

        private void MetadataCachingWithGarbageCollectionTemplate(Action garbageCollection)
        {
            MetadataWorkspace.ClearCache();
            var weakReferences = new WeakReference[3];

            // load metadata
            using (var connection1 = new EntityConnection(connectionString))
            {
                connection1.Open();

                weakReferences[0] = new WeakReference(connection1.GetMetadataWorkspace().GetItemCollection(DataSpace.CSpace));
                weakReferences[1] = new WeakReference(connection1.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace));
                weakReferences[2] = new WeakReference(connection1.GetMetadataWorkspace().GetItemCollection(DataSpace.CSSpace));
            }

            // perform necessary garbage collection steps
            garbageCollection();

            // verify that metadata was cached
            using (var connection2 = new EntityConnection(connectionString))
            {
                connection2.Open();

                Assert.Same(weakReferences[0].Target, connection2.GetMetadataWorkspace().GetItemCollection(DataSpace.CSpace));
                Assert.Same(weakReferences[1].Target, connection2.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace));
                Assert.Same(weakReferences[2].Target, connection2.GetMetadataWorkspace().GetItemCollection(DataSpace.CSSpace));
            }
        }
开发者ID:christiandpena,项目名称:entityframework,代码行数:28,代码来源:MetadataCachingTests.cs

示例4: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call Ctor with valid target reference and set trackResurrection to false");

        try
        {
            Object obj = new Object();
            WeakReference reference = new WeakReference(obj, false);

            if ((reference.TrackResurrection != false) || (!reference.Target.Equals(obj)) )
            {
                TestLibrary.TestFramework.LogError("001.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
                                                                                                                  ", reference.Target = " + reference.Target.ToString() +
                                                                                                                  ", obj = " + obj.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:29,代码来源:weakreferencector1.cs

示例5: PosTest1

    // ATTENTION!!! ATTENTION!!! ATTENTION!!!
    //
    // If you encounter issues with object lifetime, please see more comments in WeakReferenceCtor2.cs

    public bool PosTest1()
    {
        bool retVal = true;
        TestFramework.BeginScenario("Test IsAlive with short WeakReference");

        try
        {
            WeakReference extWR = new WeakReference(WRHelper.CreateAnObject("Test"), false);

            if (!extWR.IsAlive)
            {
                TestFramework.LogError("001", "WeakReference IsAlive not as expected. Expected : True; Actual: " + extWR.IsAlive);
                retVal = false;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            //Dev10 Bug #413556: WeakReference object incorrectly kept alive. Enable after the test is fixed.
            //
            //if (extWR.IsAlive)
            //{
            //    TestFramework.LogError("002", "WeakReference IsAlive not as expected. Expected : False; Actual: " + extWR.IsAlive);
            //    retVal = false;
            //}
        }
        catch (Exception e)
        {
            TestFramework.LogError("003", "Unexpected exception occured: " + e);
            retVal = false;
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:38,代码来源:weakreferenceisalive.cs

示例6: DependencyObserver

 /// <summary>
 /// Initializes a new instance of the <see cref="DependencyObserver"/> class.
 /// </summary>
 /// <param name="messageHandler">The message handler.</param>
 /// <param name="methodFactory">The method factory.</param>
 /// <param name="notifier">The notifier.</param>
 public DependencyObserver(IRoutedMessageHandler messageHandler, IMethodFactory methodFactory, INotifyPropertyChanged notifier)
 {
     _messageHandler = messageHandler;
     _methodFactory = methodFactory;
     _weakNotifier = new WeakReference<INotifyPropertyChanged>(notifier);
     _monitoringInfos = new Dictionary<string, MonitoringInfo>();
 }
开发者ID:Mrding,项目名称:Ribbon,代码行数:13,代码来源:DependencyObserver.cs

示例7: GetTargetTest

    public bool GetTargetTest()
    {
        int[] array = new int[50];
        Object[] obj = new Object[25];

        WeakReference weakarray = new WeakReference(array); // array has only weak reference

        // obj has both strong and weak ref and so should not get collected

        WeakReference weakobj = new WeakReference(obj);
        GCHandle objhandle = GCHandle.Alloc(obj, GCHandleType.Normal);

        // ensuring GC.Collect() occurs even with /debug option
        array = null;
        obj = null;

        GC.Collect();

        Object target1 = weakarray.Target; // should be null
        Object target2 = weakobj.Target;   // should be System.Object[]

        Console.WriteLine("{0},{1}", target1, target2);

        if ((target1 == null) && (target2 != null))
        {
            Console.WriteLine("Test for WeakReference.get_Target passed!");
            return true;
        }
        else
        {
            Console.WriteLine("Test for WeakReference.get_Target failed!");
            return false;
        }
    }
开发者ID:rendle-labs,项目名称:coreclr,代码行数:34,代码来源:Target.cs

示例8: VerifyObject

 public static bool VerifyObject(WeakReference wr, string s)
 {
     if (((myClass)wr.Target).myString != s)
         return false;
     else
         return true;
 }
开发者ID:l1183479157,项目名称:coreclr,代码行数:7,代码来源:helper.cs

示例9: GetTargetTest

    public bool GetTargetTest()
    {
        CreateArrays();
        WeakReference weakarray = new WeakReference(array); // array has only weak reference

        // obj has both strong and weak ref and so should not get collected

        WeakReference weakobj = new WeakReference(obj);
        GCHandle objhandle = GCHandle.Alloc(obj, GCHandleType.Normal);
        
        DestroyArrays();
        GC.Collect();

        Object target1 = weakarray.Target; // should be null
        Object target2 = weakobj.Target;   // should be System.Object[]

        Console.WriteLine("{0},{1}", target1, target2);

        if ((target1 == null) && (target2 != null))
        {
            Console.WriteLine("Test for WeakReference.get_Target passed!");
            return true;
        }
        else
        {
            Console.WriteLine("Test for WeakReference.get_Target failed!");
            return false;
        }
    }
开发者ID:geoffkizer,项目名称:coreclr,代码行数:29,代码来源:Target.cs

示例10: ActionMessageHandler

        /// <summary>
        /// Initializes a new instance of the <see cref="ActionMessageHandler"/> class.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="target">The target.</param>
        public ActionMessageHandler(IActionHost host, object target)
        {
            _weakTarget = new WeakReference<object>(target);
            _host = host;

            _host.SelectMany(x => x.Filters.HandlerAware)
                .Union(_host.Filters.HandlerAware)
                .Apply(x => x.MakeAwareOf(this));
        }
开发者ID:Mrding,项目名称:Ribbon,代码行数:14,代码来源:ActionMessageHandler.cs

示例11: SetupLinks

	static void SetupLinks () {
		var a = new Bridge () { id = "bridge" };
		var b = new Bridge () { id = "child" };
		a.link.Add (b);
		a.__test = 1;
		b.__test = 0;
		root = new WeakReference<Bridge> (a, true);
		child = new WeakReference<Bridge> (b, true);
	}
开发者ID:Zman0169,项目名称:mono,代码行数:9,代码来源:sgen-bridge-xref.cs

示例12: doWork

 public void doWork()
 {
     ServiceProvider service;
     if((provider == null) || !provider.TryGetTarget(out service)){
         service = new ServiceProvider();
         provider = new WeakReference<ServiceProvider>(service); // !!!!! podem evitar instanciar uma nova WeakReference fazendo o SetTarget(T)
     }
     service.doWork();
 }
开发者ID:isel-leic-ave,项目名称:ave-2015-16-sem1-i41n,代码行数:9,代码来源:App.cs

示例13: Swap

	static void Swap(ref WeakReference refNmsp, object o)
	{
		WeakReference wref = refNmsp;
		if (wref != null)
		{
			Console.WriteLine ("Need this to make it pass");
		}
		Interlocked.CompareExchange<WeakReference>(ref refNmsp, new WeakReference(o), wref);
	}
开发者ID:Zman0169,项目名称:mono,代码行数:9,代码来源:interlocked-4.2.cs

示例14: ObjectViewListener

        internal ObjectViewListener(IObjectView view, IList list, object dataSource)
        {
            _viewWeak = new WeakReference(view);
            _dataSource = dataSource;
            _list = list;

            RegisterCollectionEvents();
            RegisterEntityEvents();
        }
开发者ID:jimmy00784,项目名称:entityframework,代码行数:9,代码来源:ObjectViewListener.cs

示例15: DebugComponent

    public DebugComponent(Game game)
        : base(game)
    {
        // Load up our content manager
        content = new ContentManager(game.Services);

        // Create the very first weak ref instance for GC checking.
        // This will be dealt with in Update() from now on.
        this.weakReference = new WeakReference(new object());
    }
开发者ID:shadowfox,项目名称:misc,代码行数:10,代码来源:DebugComponent.cs


注:本文中的WeakReference类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。