本文整理汇总了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));
}
}
示例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);
}
}
示例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;
}
}
示例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
}
示例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
}
示例6: TransactionPropertyNode
/// <summary>
/// Constructor</summary>
public TransactionPropertyNode(ITransactionContext context)
{
if(context != null)
m_contextRef = new WeakReference(context);
else
IsReadOnly = true;
}
示例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);
}));
});
}
示例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;
}
示例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;
}
示例10: CompressedStream
public CompressedStream(Stream baseStream)
{
this.baseStream = baseStream;
localByte = new byte[1];
cache = new MemoryStream();
inBufferRef = new WeakReference(inBuffer, false);
}
示例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);
}
}
}
示例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);
}
示例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.");
}
}
示例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();
}
示例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);
}