• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# WeakReference类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: CKeyHook

    float _nPropValueStart; // Value of our CProp at start of 'quick mouse edit'

    #endregion Fields

    #region Constructors

    public CKeyHook(CProp oProp, KeyCode oKeyCode, EKeyHookType eKeyHookType, string sDescription, float nRatio=1.0f, bool bSelectedBodyOnly = true)
    {
        _oProp			= oProp;
        _oKeyCode		= oKeyCode;
        _eKeyHookType	= eKeyHookType;
        _sDescription	= sDescription;
        _nRatio			= nRatio;
        _bSelectedBodyOnly = bSelectedBodyOnly;
        _oWeakRef		= new WeakReference(this, false);
        CGame.INSTANCE._aKeyHooks.Add(_oWeakRef);		//###NOTE: Add a weak reference to CGame so that it can automatically remove dead objects as the owner of this CKeyHook destroys us.
    }
开发者ID:dvochin,项目名称:Scripts,代码行数:17,代码来源:CKeyHook.cs


示例17: SetupLinks

	static void SetupLinks () {
		var r = new Toggleref () { id = "root" };
		var c = new Toggleref () { id = "child" };
		r.link.Add (c);
		r.__test = Toggleref.STRONG;
		c.__test = Toggleref.WEAK;
		Register (r);
		Register (c);
		root = new WeakReference<Toggleref> (r, false);
		child = new WeakReference<Toggleref> (c, false);
	}
开发者ID:Numpsy,项目名称:mono,代码行数:11,代码来源:sgen-toggleref.cs


示例18: SetupLinks

	static void SetupLinks () {
		var a = new Toggleref () { id = "root" };
		var b = new Toggleref () { id = "child" };
		a.link.Add (b);
		a.__test = Toggleref.STRONG;
		b.__test = Toggleref.WEAK;
		Register (a);
		Register (b);
		root = new WeakReference<Toggleref> (a, false);
		child = new WeakReference<Toggleref> (b, false);
	}
开发者ID:nobled,项目名称:mono,代码行数:11,代码来源:sgen-toggleref.cs


示例19: Main

	static int Main ()
	{
		WeakReference wr = new WeakReference (new MainForm ());
		Application.Run ((Form) wr.Target);

		GC.Collect ();
		System.Threading.Thread.Sleep (200);
		GC.Collect ();

		return wr.IsAlive ? 1 : 0;
	}
开发者ID:mono,项目名称:gert,代码行数:11,代码来源:test.cs


示例20: UnpackedObjectCache

        static UnpackedObjectCache()
        {
            Dead = new WeakReference<Entry>(null);
            _maxByteCount = new WindowCacheConfig().DeltaBaseCacheLimit;

            Cache = new Slot[CacheSize];
            for (int i = 0; i < CacheSize; i++)
            {
                Cache[i] = new Slot();
            }
        }
开发者ID:drothmaler,项目名称:GitSharp,代码行数:11,代码来源:UnpackedObjectCache.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Weapon类代码示例发布时间:2022-05-24
下一篇:
C# WeakFunc类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap