PageRenderTime 24ms CodeModel.GetById 12ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/IronPython_Main/Runtime/Microsoft.Dynamic/Utils/WeakHandle.cs

#
C# | 58 lines | 33 code | 9 blank | 16 comment | 5 complexity | 7950e8b3d2868e16f79f7ce83bb73e22 MD5 | raw file
 1/* ****************************************************************************
 2 *
 3 * Copyright (c) Microsoft Corporation. 
 4 *
 5 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A 
 6 * copy of the license can be found in the License.html file at the root of this distribution. If 
 7 * you cannot locate the  Apache License, Version 2.0, please send an email to 
 8 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 9 * by the terms of the Apache License, Version 2.0.
10 *
11 * You must not remove this notice, or any other, from this software.
12 *
13 *
14 * ***************************************************************************/
15
16using System;
17using System.Runtime.InteropServices;
18
19namespace Microsoft.Scripting.Utils {
20
21#if SILVERLIGHT
22    // TODO: finalizers in user types aren't supported in Silverlight
23    // we need to come up with another solution for Python's _weakref library
24    public struct WeakHandle {
25        private WeakReference _weakRef;
26
27        public WeakHandle(object target, bool trackResurrection) {
28            _weakRef = new WeakReference(target, trackResurrection);
29            GC.SuppressFinalize(this._weakRef);
30        }
31
32        public bool IsAlive { get { return _weakRef != null && _weakRef.IsAlive; } }
33        public object Target { get { return _weakRef != null ? _weakRef.Target : null; } }
34
35        public void Free() {
36            if (_weakRef != null) {
37                GC.ReRegisterForFinalize(_weakRef);
38                _weakRef.Target = null;
39                _weakRef = null;
40            }
41        }
42    }
43#else
44    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] // TODO: fix
45    public struct WeakHandle {
46
47        private GCHandle weakRef;
48
49        public WeakHandle(object target, bool trackResurrection) {
50            this.weakRef = GCHandle.Alloc(target, trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak);
51        }
52
53        public bool IsAlive { get { return weakRef.IsAllocated; } }
54        public object Target { get { return weakRef.Target; } }
55        public void Free() { weakRef.Free(); }
56    }
57#endif
58}