WeakReference 클래스
정의
가비지 수집에 의한 개체 회수를 허용하면서 개체를 참조하는 약한 참조를 나타냅니다.Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection.
public ref class WeakReference : System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class WeakReference : System.Runtime.Serialization.ISerializable
type WeakReference = class
interface ISerializable
Public Class WeakReference
Implements ISerializable
- 상속
-
WeakReference
- 특성
- 구현
예제
다음 예제에서는 약한 참조를 사용 하 여 애플리케이션에 대 한 리소스로 개체의 캐시를 유지 하는 방법을 보여 줍니다.The following example demonstrates how you can use weak references to maintain a cache of objects as a resource for an application. 캐시를 사용 하 여 생성 되는 IDictionary<TKey,TValue> 의 WeakReference 인덱스 값에서 키 지정 된 개체입니다.The cache is constructed using an IDictionary<TKey,TValue> of WeakReference objects keyed by an index value. Target 에 대 한 속성을 WeakReference 개체는 데이터를 나타내는 바이트 배열에서 개체입니다.The Target property for the WeakReference objects is an object in a byte array that represents data.
이 예제에서는 캐시의 개체를 임의로 액세스합니다.The example randomly accesses objects in the cache. 가비지 컬렉션에 대 한 개체 회수를 새 데이터 개체를 다시 생성 됩니다. 그렇지 않으면 개체는 약한 참조에 액세스할 수 있습니다.If an object is reclaimed for garbage collection, a new data object is regenerated; otherwise, the object is available to access because of the weak reference.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Create the cache.
int cacheSize = 50;
Random r = new Random();
Cache c = new Cache(cacheSize);
string DataName = "";
GC.Collect(0);
// Randomly access objects in the cache.
for (int i = 0; i < c.Count; i++) {
int index = r.Next(c.Count);
// Access the object by getting a property value.
DataName = c[index].Name;
}
// Show results.
double regenPercent = c.RegenerationCount/(double)c.Count;
Console.WriteLine("Cache size: {0}, Regenerated: {1:P2}%", c.Count, regenPercent);
}
}
public class Cache
{
// Dictionary to contain the cache.
static Dictionary<int, WeakReference> _cache;
// Track the number of times an object is regenerated.
int regenCount = 0;
public Cache(int count)
{
_cache = new Dictionary<int, WeakReference>();
// Add objects with a short weak reference to the cache.
for (int i = 0; i < count; i++) {
_cache.Add(i, new WeakReference(new Data(i), false));
}
}
// Number of items in the cache.
public int Count
{
get { return _cache.Count; }
}
// Number of times an object needs to be regenerated.
public int RegenerationCount
{
get { return regenCount; }
}
// Retrieve a data object from the cache.
public Data this[int index]
{
get {
Data d = _cache[index].Target as Data;
if (d == null) {
// If the object was reclaimed, generate a new one.
Console.WriteLine("Regenerate object at {0}: Yes", index);
d = new Data(index);
_cache[index].Target = d;
regenCount++;
}
else {
// Object was obtained with the weak reference.
Console.WriteLine("Regenerate object at {0}: No", index);
}
return d;
}
}
}
// This class creates byte arrays to simulate data.
public class Data
{
private byte[] _data;
private string _name;
public Data(int size)
{
_data = new byte[size * 1024];
_name = size.ToString();
}
// Simple property.
public string Name
{
get { return _name; }
}
}
// Example of the last lines of the output:
//
// ...
// Regenerate object at 36: Yes
// Regenerate object at 8: Yes
// Regenerate object at 21: Yes
// Regenerate object at 4: Yes
// Regenerate object at 38: No
// Regenerate object at 7: Yes
// Regenerate object at 2: Yes
// Regenerate object at 43: Yes
// Regenerate object at 38: No
// Cache size: 50, Regenerated: 94%
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create the cache.
Dim cacheSize As Integer = 50
Dim r As Random = New Random()
Dim c As Cache = New Cache(cacheSize)
Dim DataName As String = ""
GC.Collect(0)
' Randomly access objects in the cache.
For ctr As Integer = 0 To C.Count - 1
Dim index As Integer = r.Next(c.Count)
' Access the object by getting a property value.
DataName = c(index).Name
Next
' Show results.
Dim regenPercent As Double = c.RegenerationCount * 100 / c.Count
Console.WriteLine("Cache size: {0}, Regenerated: {1}%", c.Count, regenPercent)
End Sub
End Class
Public Class Cache
' Dictionary to contain the cache.
Private Shared _cache As Dictionary(Of Integer, WeakReference)
' Track the number of times an object is regenerated.
Dim regenCount As Integer = 0
Public Sub New(ByVal count As Integer)
_cache = New Dictionary(Of Integer, WeakReference)
' Add data objects with a short weak reference to the cache.
For ctr = 0 To count - 1
_cache.Add(ctr, New WeakReference(New Data(ctr)))
Next
End Sub
' Number of items in the cache.
Public ReadOnly Property Count() As Integer
Get
Return _cache.Count
End Get
End Property
' Number of times an object needs to be regenerated.
Public ReadOnly Property RegenerationCount() As Integer
Get
Return regenCount
End Get
End Property
' Retrieve a data object from the cache.
Default Public ReadOnly Property Item(ByVal index As Integer) As Data
Get
Dim d As Data = TryCast(_cache(index).Target, Data)
' If the object was reclaimed, generate a new one.
If d Is Nothing Then
Console.WriteLine("Regenerate object at {0}: Yes", index)
d = New Data(index)
_cache(index).Target = d
regenCount += 1
Else
' Object was obtained with the weak reference.
Console.WriteLine("Regenerate object at {0}: No", index.ToString())
End If
Return d
End Get
End Property
End Class
' Class that creates byte arrays to simulate data.
Public Class Data
Private _data() As Byte
Private _name As String
Public Sub New(ByVal size As Integer)
_data = New Byte(((size * 1024)) - 1) {}
_name = size.ToString
End Sub
' Simple property for accessing the object.
Public ReadOnly Property Name() As String
Get
Return _name
End Get
End Property
End Class
' Example of the last lines of the output:
' ...
' Regenerate object at 36: Yes
' Regenerate object at 8: Yes
' Regenerate object at 21: Yes
' Regenerate object at 4: Yes
' Regenerate object at 38: No
' Regenerate object at 7: Yes
' Regenerate object at 2: Yes
' Regenerate object at 43: Yes
' Regenerate object at 38: No
' Cache size: 50, Regenerated: 94%
설명
약한 참조는 가비지 수집기가 개체에 액세스 하려면 애플리케이션 허용 하면서 개체를 수집할 수 있습니다.A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. 개체를 해야 하는 경우 여전히에 대 한 강한 참조를 수집 되지 않도록 방지 합니다.If you need the object, you can still obtain a strong reference to it and prevent it from being collected. 사용 하 여 short 및 long weak 방법에 대 한 자세한 내용은 참조 하세요. 약한 참조합니다.For more information about how to use short and long weak references, see Weak References.
생성자
WeakReference() | |
WeakReference(Object) |
지정된 개체를 참조하여 WeakReference 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the WeakReference class, referencing the specified object. |
WeakReference(Object, Boolean) |
지정된 개체를 참조하고 지정된 재활성화 추적을 사용하여 WeakReference 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the WeakReference class, referencing the specified object and using the specified resurrection tracking. |
WeakReference(SerializationInfo, StreamingContext) |
지정된 serialization 및 스트림 개체의 deserialize된 데이터를 사용하여 WeakReference 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the WeakReference class, using deserialized data from the specified serialization and stream objects. |
속성
IsAlive |
현재 WeakReference 개체에서 참조하는 개체가 가비지 수집되었는지 여부를 가져옵니다.Gets an indication whether the object referenced by the current WeakReference object has been garbage collected. |
Target |
현재 WeakReference 개체에서 참조하는 개체(대상)를 가져오거나 설정합니다.Gets or sets the object (the target) referenced by the current WeakReference object. |
TrackResurrection |
현재 WeakReference 개체에서 참조되는 개체가 종료된 후 추적되는지 여부를 가져옵니다.Gets an indication whether the object referenced by the current WeakReference object is tracked after it is finalized. |
메서드
Equals(Object) |
지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object. (다음에서 상속됨 Object) |
Finalize() |
현재 WeakReference 개체가 나타내는 대상에 대한 참조를 삭제합니다.Discards the reference to the target represented by the current WeakReference object. |
GetHashCode() |
기본 해시 함수로 작동합니다.Serves as the default hash function. (다음에서 상속됨 Object) |
GetObjectData(SerializationInfo, StreamingContext) |
현재 SerializationInfo 개체를 serialize하는 데 필요한 모든 데이터로 WeakReference 개체를 채웁니다.Populates a SerializationInfo object with all the data needed to serialize the current WeakReference object. |
GetType() |
현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance. (다음에서 상속됨 Object) |
MemberwiseClone() |
현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object. (다음에서 상속됨 Object) |
ToString() |
현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object. (다음에서 상속됨 Object) |
보안
SecurityPermission
비관리 코드를 호출할 수 있습니다.for the ability to call unmanaged code. 요청 값: InheritanceDemand; 권한 값: UnmanagedCodeDemand value: InheritanceDemand; Permission value: UnmanagedCode