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


C# System.WeakReference类代码示例

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


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

示例1: AddFiles

 public static void AddFiles(FileStore store, IEnumerable<WeakReference> items)
 {
     var storeRef = new WeakReference(store);
       foreach (var i in items) {
     queue.Add(new Item(storeRef, i));
       }
 }
开发者ID:Nirad,项目名称:simpleDLNA,代码行数:7,代码来源:Thumbnailer.cs

示例2: WeakActionBase

 /// <summary>
 /// Initializes a new instance of the <see cref="WeakActionBase"/> class.
 /// </summary>
 /// <param name="target">The target of the weak action.</param>
 /// <exception cref="ArgumentException">The <paramref name="target"/> is <c>null</c> or whitespace.</exception>
 protected WeakActionBase(object target)
 {
     if (target != null)
     {
         _weakTarget = new WeakReference(target);
     }
 }
开发者ID:justdude,项目名称:DbExport,代码行数:12,代码来源:WeakAction.cs

示例3: Add

        // Calls to Add must be synchronized.
        public void Add(object key, object value)
        {
            Fx.Assert(key != null, "HopperCache key cannot be null.");
            Fx.Assert(value != null, "HopperCache value cannot be null.");

            // Special-case DBNull since it can never be collected.
            if (this.weak && !object.ReferenceEquals(value, DBNull.Value))
            {
                value = new WeakReference(value);
            }

            Fx.Assert(this.strongHopper.Count <= this.hopperSize * 2,
                "HopperCache strongHopper is bigger than it's allowed to get.");

            if (this.strongHopper.Count >= this.hopperSize * 2)
            {
                Hashtable recycled = this.limitedHopper;
                recycled.Clear();
                recycled.Add(key, value);

                // The try/finally is here to make sure these happen without interruption.
                try { } finally
                {
                    this.limitedHopper = this.strongHopper;
                    this.strongHopper = recycled;
                }
            }
            else
            {
                // We do nothing to prevent things from getting added multiple times.  Also may be writing over
                // a dead weak entry.
                this.strongHopper[key] = value;
            }
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:35,代码来源:HopperCache.cs

示例4: CreateAndDisposeExplicitSetting

            public void CreateAndDisposeExplicitSetting(ReferenceHandling referenceHandling)
            {
                var x = new WithSimpleProperties { Value = 1, Time = DateTime.MinValue };
                var y = new WithSimpleProperties { Value = 1, Time = DateTime.MinValue };
                var propertyChanges = new List<string>();
                var expectedChanges = new List<string>();

                using (var tracker = Track.IsDirty(x, y, PropertiesSettings.GetOrCreate(referenceHandling)))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    CollectionAssert.IsEmpty(propertyChanges);

                    x.Value++;
                    Assert.AreEqual(true, tracker.IsDirty);
                    Assert.AreEqual("WithSimpleProperties Value x: 2 y: 1", tracker.Diff.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);
                }

                x.Value++;
                CollectionAssert.AreEqual(expectedChanges, propertyChanges);

#if (!DEBUG) // debug build keeps instances alive longer for nicer debugging experience
                var wrx = new System.WeakReference(x);
                var wry = new System.WeakReference(y);
                x = null;
                y = null;
                System.GC.Collect();
                Assert.AreEqual(false, wrx.IsAlive);
                Assert.AreEqual(false, wry.IsAlive);
#endif
            }
开发者ID:JohanLarsson,项目名称:Gu.State,代码行数:34,代码来源:DirtyTrackerTests.Simple.cs

示例5: TestPublicNestedClassInternalNamedMethod

        public void TestPublicNestedClassInternalNamedMethod()
        {
            Reset();

            const int index = 99;

            _itemPublic = new PublicNestedTestClass(index);
            _reference = new WeakReference(_itemPublic);

            _action = _itemPublic.GetAction(WeakActionTestCase.InternalNamedMethod);

            Assert.IsTrue(_reference.IsAlive);
            Assert.IsTrue(_action.IsAlive);

            _action.Execute();

            Assert.AreEqual(
                PublicNestedTestClass.Expected + PublicNestedTestClass.Internal + index,
                PublicNestedTestClass.Result);

            _itemPublic = null;
            GC.Collect();

#if SILVERLIGHT
            Assert.IsTrue(_reference.IsAlive); // Anonymous, private and internal methods cannot be GCed
            _action = null;
            GC.Collect();
            Assert.IsFalse(_reference.IsAlive);
#else
            Assert.IsFalse(_reference.IsAlive);
#endif
        }
开发者ID:NulledLabs,项目名称:mvvmlight,代码行数:32,代码来源:WeakActionNestedTest.cs

示例6: TransactionPropertyNode

 /// <summary>
 /// Constructor</summary>
 public TransactionPropertyNode(ITransactionContext context)
 {
     if(context != null)
         m_contextRef = new WeakReference(context);
     else
         IsReadOnly = true;
 }
开发者ID:Joxx0r,项目名称:ATF,代码行数:9,代码来源:TransactionPropertyNode.cs

示例7: ViewDidLoad

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            var vm = (RepositoriesExploreViewModel)ViewModel;
            var search = (UISearchBar)TableView.TableHeaderView;

            TableView.RowHeight = UITableView.AutomaticDimension;
            TableView.EstimatedRowHeight = 64f;

            var weakVm = new WeakReference<RepositoriesExploreViewModel>(vm);
            BindCollection(vm.Repositories, repo =>
            {
                var description = vm.ShowRepositoryDescription ? repo.Description : string.Empty;
                var avatar = new GitHubAvatar(repo.Owner?.AvatarUrl);
                var sse = new RepositoryElement(repo.Name, repo.StargazersCount, repo.ForksCount, description, repo.Owner.Login, avatar) { ShowOwner = true };
                sse.Tapped += MakeCallback(weakVm, repo);
                return sse;
            });

            OnActivation(d =>
            {
                d(search.GetChangedObservable().Subscribe(x => vm.SearchText = x));
                d(vm.Bind(x => x.IsSearching).SubscribeStatus("Searching..."));
                d(search.GetSearchObservable().Subscribe(_ => {
                    search.ResignFirstResponder();
                    vm.SearchCommand.Execute(null);
                }));
            });
        }
开发者ID:RaineriOS,项目名称:CodeHub,代码行数:29,代码来源:RepositoriesExploreView.cs

示例8: ColumnsCollectionsChanged

        public static void ColumnsCollectionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var grid = d as GridViewDataControl;
            if (grid == null)
            {
                return;
            }

            _grid = new WeakReference(grid);
            grid.Columns.Clear();
            grid.Unloaded += _grid_Unloaded;
            var collection = (ColumnCollection)e.NewValue;

            if (collection == null)
            {
                return;
            }

            _collection = new WeakReference(collection);

            if (collection.Any())
            {
                foreach (var column in collection)
                {
                    AddColumnToGrid(grid, column);
                }
            }

            collection.CollectionChanged -= _collection_CollectionChanged;
            collection.CollectionChanged += _collection_CollectionChanged;
        }
开发者ID:mparsin,项目名称:Elements,代码行数:31,代码来源:RadGridViewHelper.cs

示例9: ObjectReference

 /// <summary>
 /// Initializes a new instance of the <see cref="ObjectReference"/> class.
 /// </summary>
 /// <param name="creationTime">The creation time.</param>
 /// <param name="comObject">The com object to track.</param>
 /// <param name="stackTrace">The stack trace.</param>
 public ObjectReference(DateTime creationTime, ComObject comObject, string stackTrace)
 {
     CreationTime = creationTime;
     // Creates a long week reference to the ComObject
     Object = new WeakReference(comObject, true);
     StackTrace = stackTrace;
 }
开发者ID:alexey-bez,项目名称:SharpDX,代码行数:13,代码来源:ObjectReference.cs

示例10: CompressedStream

        public CompressedStream(Stream baseStream)
        {
            this.baseStream = baseStream;
            localByte = new byte[1];
			cache = new MemoryStream();
            inBufferRef = new WeakReference(inBuffer, false);
        }
开发者ID:maanshancss,项目名称:ClassLibrary,代码行数:7,代码来源:CompressedStream.cs

示例11: WeakReference

		/// <summary>
		/// Gets or sets cached data
		/// </summary>
		/// <value>The cached object or <c>null</c></value>
		public object this[object key]
		{
			get
			{
				var wr = _cache[key] as WeakReference;
				if (wr == null || !wr.IsAlive)
				{
					_cache.Remove(key);
					return null;
				}

				return wr.Target;
			}
			set
			{
				if (value == null)
				{
					_cache.Remove(key);
				}
				else
				{
					_cache[key] = new WeakReference(value);
				}
			}
		}
开发者ID:mynew4,项目名称:DAoC,代码行数:29,代码来源:SimpleCache.cs

示例12: Into

        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        /// <param name="imageScale">Optional scale factor to use when interpreting the image data. If unspecified it will use the device scale (ie: Retina = 2, non retina = 1)</param>
        public static IScheduledWork Into(this TaskParameter parameters, UIImageView imageView, float imageScale = -1f)
        {
            var weakRef = new WeakReference<UIImageView>(imageView);
            Func<UIImageView> getNativeControl = () => {
                UIImageView refView;
                if (!weakRef.TryGetTarget(out refView))
                    return null;
                return refView;
            };

			Action<UIImage, bool> doWithImage = (img, fromCache) => {
                UIImageView refView = getNativeControl();
                if (refView == null)
                    return;

				var isFadeAnimationEnabled = parameters.FadeAnimationEnabled.HasValue ? 
					parameters.FadeAnimationEnabled.Value : ImageService.Config.FadeAnimationEnabled;

				if (isFadeAnimationEnabled && !fromCache)
				{
					// fade animation
					UIView.Transition(refView, 0.4f, 
						UIViewAnimationOptions.TransitionCrossDissolve 
						| UIViewAnimationOptions.BeginFromCurrentState,
						() => { refView.Image = img; },
						() => {  });
				}
				else
				{
					refView.Image = img;
				}
            };

            return parameters.Into(getNativeControl, doWithImage, imageScale);
        }
开发者ID:nukedbit,项目名称:FFImageLoading,代码行数:41,代码来源:TaskParameterExtensions.cs

示例13: Main

        static void Main()
        {
            // Instantiate a weak reference to MathTest object
             WeakReference mathReference = new WeakReference(new MathTest());
             MathTest math;
             if(mathReference.IsAlive)
             {
            math = mathReference.Target as MathTest;
            math.Value = 30;
            Console.WriteLine(
               "Value field of math variable contains " + math.Value);
            Console.WriteLine("Square of 30 is " + math.GetSquare());

             }
             else
             {
            Console.WriteLine("Reference is not available.");
             }

             GC.Collect();

             if(mathReference.IsAlive)
             {
            math = mathReference.Target as MathTest;
             }
             else
             {
            Console.WriteLine("Reference is not available.");
             }
        }
开发者ID:ianheyi,项目名称:CSharp,代码行数:30,代码来源:MathTestWeakReference.cs

示例14: PropertyChanged_should_call_weakly_subscribed_handler_when_handler_is_collected

        public void PropertyChanged_should_call_weakly_subscribed_handler_when_handler_is_collected()
        {
            // Arrange
            var observer = new Observer();
            var model = new SomeModel(observer);
            Action<int> onChange = model.Change;
            var weakOnChange = new WeakReference(onChange);

            var counter = Reactive.Of(0);
            counter.PropertyChanged +=
                (sender, args) =>
                {
                    var handler = weakOnChange.Target as Action<int>;
                    if (handler != null)
                        handler(counter);
                };

            // Act
            onChange = null;
            GC.Collect();
            counter.Value = 1;

            // Assert
            observer.ChangedObserved.Should().BeFalse();
        }
开发者ID:EamonNerbonne,项目名称:FunTools,代码行数:25,代码来源:ReactiveWeakSubscriptionTests.cs

示例15: TestInternalNestedClassAnonymousStaticMethod

        public void TestInternalNestedClassAnonymousStaticMethod()
        {
            Reset();

            _itemInternal = new InternalNestedTestClass();
            _reference = new WeakReference(_itemInternal);

            _action = _itemInternal.GetFunc(WeakActionTestCase.AnonymousStaticMethod);

            Assert.IsTrue(_reference.IsAlive);
            Assert.IsTrue(_action.IsAlive);

            string result = _action.Execute();

            Assert.AreEqual(
                InternalNestedTestClass.Expected,
                InternalNestedTestClass.Result);
            Assert.AreEqual(
                InternalNestedTestClass.Expected,
                result);

            _itemInternal = null;
            GC.Collect();

            Assert.IsFalse(_reference.IsAlive);
        }
开发者ID:jprofi,项目名称:MSProjects,代码行数:26,代码来源:WeakFuncNestedTest.cs


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