Commit d3143796 authored by Ben Lambell's avatar Ben Lambell

Cutting down on memory consumption for ReceiverCollection

parent 86387b9c
......@@ -15,27 +15,30 @@ namespace Recurse.Common.Messaging
[Serializable]
public class ReceiverCollection<TReceiver> : IReceiverCollection<TReceiver>
{
private readonly List<object> _receivers = new List<object>();
private List<object> _receivers;
public virtual void Add(TReceiver receiver)
{
if (receiver == null)
throw new ArgumentNullException();
_receivers.Add(receiver);
GetOrCreateReceivers().Add(receiver);
}
public virtual void AddWeak(TReceiver receiver)
{
if (receiver == null)
throw new ArgumentNullException();
_receivers.Add(new WeakReference(receiver));
GetOrCreateReceivers().Add(new WeakReference(receiver));
}
public virtual void Remove(TReceiver receiver)
{
var index = _receivers.FindIndex(e => Contains(e, receiver));
if (index != -1)
_receivers.RemoveAt(index);
if (_receivers != null)
{
var index = _receivers.FindIndex(e => Contains(e, receiver));
if (index != -1)
_receivers.RemoveAt(index);
}
}
public void ForEach(Action<TReceiver> action)
......@@ -53,33 +56,43 @@ namespace Recurse.Common.Messaging
}
}
private List<object> GetOrCreateReceivers()
{
if (_receivers == null)
_receivers = new List<object>();
return _receivers;
}
private IEnumerable<TReceiver> GetReceivers()
{
for (var i = 0; i < _receivers.Count; i++)
if (_receivers != null)
{
var current = _receivers[i];
var weakReference = current as WeakReference;
if (weakReference != null)
for (var i = 0; i < _receivers.Count; i++)
{
var receiver = (TReceiver)weakReference.Target;
if (receiver != null)
var current = _receivers[i];
var weakReference = current as WeakReference;
if (weakReference != null)
{
yield return receiver;
var receiver = (TReceiver)weakReference.Target;
if (receiver != null)
{
yield return receiver;
}
else
{
_receivers.RemoveAt(i);
}
}
else
{
_receivers.RemoveAt(i);
var receiver = (TReceiver)current;
yield return receiver;
}
}
else
{
var receiver = (TReceiver)current;
yield return receiver;
}
}
}
private bool Contains(object receiver, TReceiver target)
private static bool Contains(object receiver, TReceiver target)
{
var weakReference = receiver as WeakReference;
return weakReference != null ?
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment