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(); }
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; }
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 }
public void TestPublicNestedClassPublicNamedMethod() { Reset(); const int index = 99; _itemPublic = new PublicNestedTestClass(index); _action = _itemPublic.GetAction(WeakActionTestCase.PublicNamedMethod); _reference = new WeakReference(_itemPublic); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(); Assert.AreEqual( PublicNestedTestClass.Expected + PublicNestedTestClass.Public + index, PublicNestedTestClass.Result); _itemPublic = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); }
/// <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); } }
/// <summary> /// 重建站点缓存 /// </summary> public static void RebuiltSitesCache() { //释放资源 site_ref = null; //重新赋值 if (sites != null) { for (int i = 0; i < sites.Count; i++) { sites.Remove(sites[i]); } } sites = ServiceCall.Instance.SiteService.GetSites(); //指定弱引用 site_ref = new WeakReference(sites); if (OnSiteCacheBuilding != null) { OnSiteCacheBuilding(); } }
/// <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); }
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); })); }); }
/// <summary> /// 重建模块缓存 /// </summary> public static void RebuiltModule() { //释放资源 module_ref = null; //重新赋值 if (modules != null) { for (int i = 0; i < modules.Count; i++) { modules.Remove(modules[i]); } } modules = dal.GetModules(); //指定弱引用 module_ref = new WeakReference(modules); if (OnModuleBuilting != null) { OnModuleBuilting(); } }
public CompressedStream(Stream baseStream) { this.baseStream = baseStream; localByte = new byte[1]; cache = new MemoryStream(); inBufferRef = new WeakReference(inBuffer, false); }
public void WeakReference() { var stringBuilder = new StringBuilder("test"); var weakReference = new WeakReference<StringBuilder>(stringBuilder); Assert.IsNotNull(weakReference.Target); Assert.IsInstanceOfType(weakReference.Target, typeof(StringBuilder)); Assert.AreEqual("test", weakReference.Target.ToString()); weakReference = new WeakReference<StringBuilder>(stringBuilder, trackResurrection: true); Assert.IsNotNull(weakReference.Target); Assert.IsInstanceOfType(weakReference.Target, typeof(StringBuilder)); Assert.IsTrue(weakReference.TrackResurrection); Assert.AreEqual("test", weakReference.Target.ToString()); weakReference = new WeakReference<StringBuilder>(stringBuilder, trackResurrection: false); Assert.IsNotNull(weakReference.Target); Assert.IsInstanceOfType(weakReference.Target, typeof(StringBuilder)); Assert.IsFalse(weakReference.TrackResurrection); Assert.AreEqual("test", weakReference.Target.ToString()); stringBuilder = new StringBuilder("test2"); weakReference.Target = stringBuilder; Assert.IsNotNull(weakReference.Target); Assert.IsInstanceOfType(weakReference.Target, typeof(StringBuilder)); Assert.IsFalse(weakReference.TrackResurrection); Assert.AreEqual("test2", weakReference.Target.ToString()); GC.KeepAlive(stringBuilder); }
public void Reset() { _recipient = null; _recipientInternal = null; _recipientPrivate = null; _recipientReference = null; }
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)); } }
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 }
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); }
public void TestPublicClassPublicStaticMethod() { Reset(); _itemPublic = new PublicTestClass(); _reference = new WeakReference(_itemPublic); _action = _itemPublic.GetFunc(WeakActionTestCase.PublicStaticMethod); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); var result = _action.Execute(); Assert.AreEqual( PublicTestClass.Expected + PublicTestClass.PublicStatic, PublicTestClass.Result); Assert.AreEqual( PublicTestClass.Expected + PublicTestClass.PublicStatic, result); _itemPublic = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); }
public BaseTypeNodeImpl(ITreeNodeGroup treeNodeGroup, ITypeDefOrRef typeDefOrRef, bool isBaseType) { TreeNodeGroup = treeNodeGroup; this.isBaseType = isBaseType; // Keep weak refs to them so we won't prevent removed modules from being GC'd. weakRefTypeDefOrRef = new WeakReference(typeDefOrRef); weakRefResolvedTypeDef = new WeakReference(null); }
public ViewShowcaseStep(Activity activity, int viewId) { this.parentActivity = new WeakReference<Activity>(activity); this.viewId = viewId; Setup(); }
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."); } }
/// <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); } } }
// 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; } }
/// <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; }
public static void UpdateBinding(object sender, DependencyPropertyChangedEventArgs args) { if (sender == null) return; span = new WeakReference(sender); ((Span)span.Target).Inlines.Clear(); INotifyCollectionChanged newSource = args.NewValue as INotifyCollectionChanged; INotifyCollectionChanged oldSource = args.OldValue as INotifyCollectionChanged; if (oldSource != null) oldSource.CollectionChanged -= OnSourceCollectionChanged; if (newSource == null) return; // Detach our View from the ViewModel source //EDIT: Bug fix to reflect PB7's new UI model. newSource.CollectionChanged -= OnSourceCollectionChanged; IEnumerable ns = newSource as IEnumerable; OnSourceCollectionChanged(ns, null); newSource.CollectionChanged += OnSourceCollectionChanged; }
/// <summary> /// Constructor</summary> public TransactionPropertyNode(ITransactionContext context) { if(context != null) m_contextRef = new WeakReference(context); else IsReadOnly = true; }
private void InvokeOutcomeFunction(TransactionStatus status) { WeakReference weakRealTransaction = null; lock (this) { if (this.haveIssuedOutcome) { return; } this.haveIssuedOutcome = true; this.savedStatus = status; weakRealTransaction = this.weakRealTransaction; } if (weakRealTransaction != null) { RealOletxTransaction target = weakRealTransaction.Target as RealOletxTransaction; if (target != null) { target.FireOutcome(status); if (target.phase0EnlistVolatilementContainerList != null) { foreach (OletxPhase0VolatileEnlistmentContainer container in target.phase0EnlistVolatilementContainerList) { container.OutcomeFromTransaction(status); } } if (((TransactionStatus.Aborted == status) || (TransactionStatus.InDoubt == status)) && (target.phase1EnlistVolatilementContainer != null)) { target.phase1EnlistVolatilementContainer.OutcomeFromTransaction(status); } } weakRealTransaction.Target = null; } }
static void WeakReference_TrackResurrection(JSVCall vc) { System.WeakReference _this = (System.WeakReference)vc.csObj; var result = _this.TrackResurrection; JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(result)); }
static void Main() { // Создать слабую ссылку на объект MathTest var weakReference = new System.WeakReference(new MathTest()); var math = weakReference.Target as MathTest; if (math != null) { math.Value = 30; Console.WriteLine("Value field of math variable contains {0}", math.Value); Console.WriteLine("Square of 30 is {0}", math.GetSquare(30)); } else { Console.WriteLine("Reference is not available"); // Ссылка стала недоступна } GC.Collect(); if (weakReference.IsAlive) { // ReSharper disable once RedundantAssignment math = weakReference.Target as MathTest; } else { Console.WriteLine("Reference is not available"); } Console.ReadKey(); }
void eCX() { System.Web.Security.MembershipPasswordException qTY = new System.Web.Security.MembershipPasswordException(); System.Exception tOOK = new System.Exception(); System.Threading.SynchronizationContext MaH = new System.Threading.SynchronizationContext(); System.Web.UI.WebControls.WebParts.PageCatalogPart ayRmRe = new System.Web.UI.WebControls.WebParts.PageCatalogPart(); System.Web.Security.DefaultAuthenticationModule Exmkenb = new System.Web.Security.DefaultAuthenticationModule(); System.Web.SessionState.SessionStateModule TmbqbT = new System.Web.SessionState.SessionStateModule(); System.ResolveEventArgs cGQ = new System.ResolveEventArgs("oYfQTFJiOZSVw"); System.Web.UI.ControlValuePropertyAttribute LIX = new System.Web.UI.ControlValuePropertyAttribute("zCbHRvFJUat", 910602186); System.Runtime.InteropServices.SetWin32ContextInIDispatchAttribute rfLFm = new System.Runtime.InteropServices.SetWin32ContextInIDispatchAttribute(); System.Net.HttpListenerException tIez = new System.Net.HttpListenerException(2135436060, "NJgG"); System.WeakReference mKrXQJ = new System.WeakReference(1723804374); System.Web.Configuration.OutputCacheProfile atJh = new System.Web.Configuration.OutputCacheProfile("ArZxwFnPdDdni"); System.ParamArrayAttribute TyUXndy = new System.ParamArrayAttribute(); System.Runtime.Serialization.OnDeserializingAttribute lVgFArZ = new System.Runtime.Serialization.OnDeserializingAttribute(); System.Data.SqlTypes.TypeNumericSchemaImporterExtension QbBDir = new System.Data.SqlTypes.TypeNumericSchemaImporterExtension(); System.Windows.Forms.ListViewGroup MvRc = new System.Windows.Forms.ListViewGroup("ELItUnvMGVWDmEGD"); System.ComponentModel.Design.CheckoutException NwMcuF = new System.ComponentModel.Design.CheckoutException("QdlJvFMgCKYGHpcTb"); System.Globalization.RegionInfo tAChNgq = new System.Globalization.RegionInfo(2015922813); System.Web.UI.WebControls.ValidationSummary kcldBEv = new System.Web.UI.WebControls.ValidationSummary(); System.Windows.Forms.RelatedImageListAttribute PFSRAV = new System.Windows.Forms.RelatedImageListAttribute("ZtfKTawcAmWr"); System.Web.UI.WebControls.TableSectionStyle ehekxI = new System.Web.UI.WebControls.TableSectionStyle(); System.ComponentModel.ByteConverter oodnW = new System.ComponentModel.ByteConverter(); System.Web.UI.WebControls.DetailsViewPageEventArgs NFia = new System.Web.UI.WebControls.DetailsViewPageEventArgs(599344366); System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNotation Savfrr = new System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNotation(); }
public void RemoveHandler(object o, System.Reflection.MethodInfo method) { //if (!obj) // return; if (obj == null) { return; } System.Collections.Generic.List <Oranikle.Studio.Controls.WeakDelegate <T> > .Enumerator enumerator = obj.GetEnumerator(); try { while (enumerator.MoveNext()) { Oranikle.Studio.Controls.WeakDelegate <T> weakDelegate = enumerator.Current; System.WeakReference weakReference = weakDelegate.Obj; object obj1 = weakReference.Target; if ((obj1 == o) && (weakDelegate.Method == method)) { obj.Remove(weakDelegate); return; } } } finally { enumerator.Dispose(); } }
public IEnumerator GCCollectObjectsCoro() { object a = new object(); var wa = new System.WeakReference(a); Assert.IsTrue(wa.IsAlive); Collect(); Assert.IsTrue(wa.IsAlive); a = null; Collect(); // GC.Collect will only collect if run at least a frame after an object has been destroyed for (int i = 0; i < 10; ++i) { yield return(null); Assert.IsTrue(wa.IsAlive, "Collect seems to need yielding to work"); } yield return(null); Collect(); Assert.IsFalse(wa.IsAlive); }
// fields // properties static void WeakReference_IsAlive(JSVCall vc) { System.WeakReference _this = (System.WeakReference)vc.csObj; var result = _this.IsAlive; JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(result)); }
/// <summary> Deregisters a cursor from the list to be notified of changes. /// /// </summary> /// <param name="cursor"> the cursor to deregister /// </param> protected internal virtual void unregisterCursor(Cursor cursor) { //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilIteratorhasNext_3"' for (System.Collections.IEnumerator it = cursors.GetEnumerator(); it.MoveNext();) { //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilIteratornext_3"' System.WeakReference ref_Renamed = (System.WeakReference)it.Current; //UPGRADE_ISSUE: Method 'java.lang.ref.Reference.get' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javalangrefReference_3"' Cursor cur = (Cursor)ref_Renamed.get_Renamed(); if (cur == null) { // some other unrelated cursor object has been // garbage-collected; let's take the opportunity to // clean up the cursors list anyway.. //UPGRADE_ISSUE: Method 'java.util.Iterator.remove' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javautilIteratorremove_3"' it.remove(); } else if (cur == cursor) { //UPGRADE_ISSUE: Method 'java.lang.ref.Reference.clear' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javalangrefReference_3"' ref_Renamed.clear(); //UPGRADE_ISSUE: Method 'java.util.Iterator.remove' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javautilIteratorremove_3"' it.remove(); break; } } }
//Management internal EventObject(string aEvent, object aDispatcher) { this._event = aEvent; this._dispatcher = new System.WeakReference(aDispatcher); Init(); }
public static void SetCurrentActivity(Activity activity, bool clear) { bool changed = false; lock (CurrentActivityLocker) { var currentActivity = CurrentActivity; if (clear) { if (ReferenceEquals(currentActivity, activity)) { _activityRef = Empty.WeakReference; changed = true; } } else if (!ReferenceEquals(currentActivity, activity)) { _activityRef = ServiceProvider.WeakReferenceFactory(activity); changed = true; } } if (changed) { var handler = CurrentActivityChanged; if (handler != null) { handler(activity, EventArgs.Empty); } } }
private static void DoesNotLeakTrackedProperty() { Console.WriteLine("Press any key to allocate."); Console.ReadKey(); var x = new With <ComplexType> { ComplexType = new ComplexType("a", 1) }; var y = new With <ComplexType> { ComplexType = new ComplexType("a", 1) }; using (var tracker = Track.IsDirty(x, y)) { var wrxc = new System.WeakReference(x.ComplexType); Console.WriteLine("before: {0}", wrxc.IsAlive); x.ComplexType = null; Console.WriteLine("Press any key to GC.Collect()."); Console.ReadKey(); GC.Collect(); Console.WriteLine("after: {0}", wrxc.IsAlive); Console.WriteLine("Press any key to exit."); Console.ReadKey(); //var wryc = new System.WeakReference(y.ComplexType); //y.ComplexType = null; //System.GC.Collect(); //Assert.AreEqual(false, wryc.IsAlive); } }
private void TrySetupSteps(DriverType driverType, SeleniteTest test, IWebDriver webDriver) { if (test.TestCollection.SetupSteps.IsNullOrNotAny()) return; var fileName = String.IsNullOrWhiteSpace(test.TestCollection.SetupStepsFile) ? test.TestCollection.ResolvedFile : test.TestCollection.SetupStepsFile; foreach (var pair in _setupStepsMap) { if (pair.Key.Target != webDriver) continue; if (pair.Value.Any(f => String.Equals(f, fileName, StringComparison.InvariantCultureIgnoreCase))) return; } foreach (var setupStep in test.TestCollection.SetupSteps) _testService.ExecuteTest(webDriver, driverType, setupStep, true); var weakReference = new WeakReference(webDriver); var testFiles = new List<string> { fileName }; _setupStepsMap.Add(weakReference, testFiles); }
/// <value> /// Creates record /// </value> public PrevCheckup(bool aValidMapping, object aTarget, object aItems) { IsValidMapping = aValidMapping; Target = new WeakReference (aTarget); Items = new WeakReference (aItems); fmapp = true; }
public LocalEventKeyInfo(string key, ulong id, MessageStore<Message> store) { // Don't hold onto MessageStores that would otherwise be GC'd _storeReference = new WeakReference(store); Key = key; Id = id; }
public void CreateAndDisposeExplicitSetting(ReferenceHandling referenceHandling) { var source = new WithSimpleProperties { Value1 = 1, Time = DateTime.MinValue }; var propertyChanges = new List <string>(); var expectedPropertyChanges = new List <string>(); var changes = new List <EventArgs>(); using (var tracker = Track.Changes(source, referenceHandling)) { tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName); tracker.Changed += (_, e) => changes.Add(e); CollectionAssert.IsEmpty(propertyChanges); CollectionAssert.IsEmpty(changes); source.Value1++; Assert.AreEqual(1, tracker.Changes); expectedPropertyChanges.AddRange(new[] { "Changes" }); CollectionAssert.AreEqual(expectedPropertyChanges, propertyChanges); var expected = new[] { RootChangeEventArgs.Create(ChangeTrackerNode.GetOrCreate(source, tracker.Settings, isRoot: false).Value, new PropertyChangeEventArgs(source, source.GetProperty(nameof(source.Value1)))) }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } source.Value1++; CollectionAssert.AreEqual(expectedPropertyChanges, propertyChanges); #if !DEBUG // debug build keeps instances alive longer for nicer debugging experience var wrx = new System.WeakReference(source); source = null; System.GC.Collect(); Assert.AreEqual(false, wrx.IsAlive); #endif }
// gets the parsed version of a string expression public Expression this[string expression] { get { Expression x; WeakReference wr; if (_dct.TryGetValue(expression, out wr) && wr.IsAlive) { x = wr.Target as Expression; } else { // remove all dead references from dictionary if (wr != null && _dct.Count > 100 && _hitCount++ > 100) { RemoveDeadReferences(); _hitCount = 0; } // store this expression x = _ce.Parse(expression); _dct[expression] = new WeakReference(x); } return x; } }
static void Main(string[] args) { string s1 = "abc"; string s2 = "123"; Console.WriteLine(s1 == s2); bool b = object.ReferenceEquals(s1, s2); Console.WriteLine(b); string s3 = s2; b = object.ReferenceEquals(s2, s3); Console.WriteLine(b); Console.WriteLine("======Point======="); Point p1 = new Point(3, 5); Point p2 = new Point(3, 5); Console.WriteLine(p1 == p2); Console.WriteLine(object.ReferenceEquals(p1, p2)); WeakReference wr = new WeakReference(p1); Console.WriteLine("======string======="); string s4 = "abc"; string s5 = "abc"; //因为有字符串拘留池的存在,所以仅有一个字符串的实例存在 Console.WriteLine(object.ReferenceEquals(s4, s5)); Console.WriteLine("======string======="); string s6 = "123"; string s7 = new string("123".ToCharArray());//new相当于是说强制重新创建一个字符串 Console.WriteLine(object.ReferenceEquals(s6, s7)); }
public WeakEventHandler(System.EventHandler eventHandler, Oranikle.Studio.Controls.UnregisterCallback unregister) { m_TargetRef = new System.WeakReference(eventHandler.Target); m_OpenHandler = (Oranikle.Studio.Controls.WeakEventHandler <T> .OpenEventHandler)System.Delegate.CreateDelegate(typeof(Oranikle.Studio.Controls.WeakEventHandler <T> .OpenEventHandler), null, eventHandler.Method); m_Handler = new System.EventHandler(Invoke); m_Unregister = unregister; }
public OptionSelector() { Options = new ObservableCollection <UIElement>(); System.WeakReference wr = new System.WeakReference(this); this.Initialized += (s, e) => { ((OptionSelector)wr.Target).OnInitialized(s, e); }; this.InitializeComponent(); }
public MainWindow() { System.WeakReference wr = new System.WeakReference(this); this.Loaded += (s, e) => { ((MainWindow)wr.Target).OnLoaded(s, e); }; this.SizeChanged += (s, e) => { ((MainWindow)wr.Target).OnSizeChanged(s, e); }; this.InitializeComponent(); }
/// <summary> /// Initializes a new WeakReferenceMethode object. /// </summary> /// <param name="callback">Delegate of the methode which should be called.</param> public WeakRefernceMethod(System.Action callback) // ^-> here the address is blocked. // Garbage Collection cannot remove the owner { this._CallbackMethod = new WeakReference(callback); // ^-> now the address of the delegate isn't blocked // any longer. If is needed the garbage collection can remove the owner }
void OnTriggerEnter(Collider other) { FoodBehaviour food = other.GetComponent <FoodBehaviour>(); if (food) { ImTouchingThisFood = new System.WeakReference <FoodBehaviour>(food); } }
private void DownloadImage(object state) { Deployment.Current.Dispatcher.BeginInvoke(() => { System.Diagnostics.Debug.WriteLine("ReIncarnation {0}", state.ToString()); bitmapImage = new WeakReference(new BitmapImage(new Uri(state as string))); NotifyPropertyChanged("SmallImageSource"); } ); }
public HaulExplicitlyInventoryRecord(Thing initial, HaulExplicitlyPosting parentPosting) { _parentPosting = new System.WeakReference(parentPosting); items.Add(initial); itemDef = initial.def; itemStuff = initial.Stuff; miniDef = (initial as MinifiedThing)?.InnerThing.def; selectedQuantity = initial.stackCount; ResetMerge(); }
public TransientData(tk2dSpriteCollectionData data) { name = data.spriteCollectionName; dataWeakRef = new System.WeakReference(data); if (data.needMaterialInstance) { createdMaterials = data.materialInsts; createdTextures = data.textureInsts; } }
void OnTriggerExit(Collider other) { FoodBehaviour food = other.GetComponent <FoodBehaviour>(); FoodBehaviour imTouchingThisFood; if (ImTouchingThisFood != null && ImTouchingThisFood.TryGetTarget(out imTouchingThisFood) && food == imTouchingThisFood) { ImTouchingThisFood = null; } }
public void Dispose() { if (bundle_ != null) { bundle_.UnloadAsset(name_); bundle_ = null; } assets_.Remove(name_); asset_ = null; }
private void OnCollisionEnter(Collision collision) { if (collision.collider.CompareTag("Toy")) { ToyBehaviour toy = collision.collider.GetComponent <ToyBehaviour>(); if (toy) { ImTouchingThisToy = new System.WeakReference <ToyBehaviour>(toy); } } }
protected virtual void Awake() { if (_instance == null) { _instance = new System.WeakReference(this); } else if ((T)_instance.Target != null && _instance.IsAlive && (T)_instance.Target != this) { Destroy(gameObject); } }
public HashableWeakRef(T aTarget) { if (aTarget != null) { _weakReference = new System.WeakReference(aTarget); _hashcode = aTarget.GetHashCode(); } else { throw new InvalidOperationException("Can't create HashableWeakRef out of a null reference!"); } }
/* * private Dictionary<Camera, Camera> m_ReflectionCameras = new Dictionary<Camera, Camera>(); // Camera -> Camera table * private Dictionary<Camera, Camera> m_RefractionCameras = new Dictionary<Camera, Camera>(); // Camera -> Camera table * private RenderTexture m_ReflectionTexture; * public int textureSize = 256; * private int m_OldReflectionTextureSize; * private static bool s_InsideWater; * * public LayerMask reflectLayers = -1; * public float clipPlaneOffset = 0.07f;*/ //在HexSubMapView.cs中的HexSubMapView.InitBg中被引用 //初始化来自Hex的数据 public void Init(HEX hex, int x, int y) { _weak_hex = new System.WeakReference(hex); _x = x; _y = y; int z = (x + 1) * hex.xTile - hex.xMax; int w = (y + 1) * hex.yTile - hex.yMax; _xTile = z > 0 ? hex.xTile - z : hex.xTile; _yTile = w > 0 ? hex.xTile - w : hex.yTile; GenMeshWithBound(hex); GenHexMesh(hex); }
internal void Destroy() { if (_onDestroyCallback != null) { _onDestroyCallback(this); _onDestroyCallback = null; } _event = ""; _params = null; _dispatcher = null; _listenerList.Clear(); }
public void GCCollectObjects() { object a = new object(); var wa = new System.WeakReference(a); Assert.IsTrue(wa.IsAlive); Collect(); Assert.IsTrue(wa.IsAlive); a = null; Collect(); Assert.IsTrue(wa.IsAlive, "Why oh why does it not get collected?"); }
static void WeakReference_Target(JSVCall vc) { if (vc.bGet) { System.WeakReference _this = (System.WeakReference)vc.csObj; var result = _this.Target; JSMgr.datax.setWhatever((int)JSApi.SetType.Rval, result); } else { System.Object arg0 = (System.Object)JSMgr.datax.getWhatever((int)JSApi.GetType.Arg); System.WeakReference _this = (System.WeakReference)vc.csObj; _this.Target = arg0; } }
public void Add(string key, Object obj) { if (elementDict == null) { elementDict = new Dictionary <string, System.WeakReference>(); } var refObj = new System.WeakReference(obj); if (elementDict.ContainsKey(key)) { Debug.LogWarning("key:" + key + " existed, overwrite it"); } elementDict[key] = refObj; }
/// <summary> /// Adds the specified ev. /// </summary> /// <param name="eh">The eh.</param> public void Add(T eh) { if (eh != null) { Delegate d = (Delegate)(object)eh; if (eventEntries.Count == eventEntries.Capacity) { RemoveDeadEntries(); } MethodInfo targetMethod = d.Method; object targetInstance = d.Target; System.WeakReference target = targetInstance != null ? new System.WeakReference(targetInstance) : null; eventEntries.Add(new EventEntry(FastSmartWeakEventForwarderProvider.GetForwarder(targetMethod), targetMethod, target)); } }