Click here to Skip to main content
15,892,059 members
Articles / Programming Languages / C#

Tweaked Events

Rate me:
Please Sign up or sign in to vote.
4.83/5 (12 votes)
18 Dec 2010MIT18 min read 34.8K   289   41  
Framework for customizing events. Comes with Weak Events and Synced Events
using System;

namespace JpLabs.TweakedEvents
{
	public sealed class WeakEventEntry<TEH> : BaseEventEntry<TEH> where TEH : class
	{
		private WeakEventForwarderProvider.ForwarderDelegate forwarder;
		private SinglecastWeakDelegate delegateRef;

		public WeakEventEntry(TEH handler)
		{
			if (handler == null) throw new ArgumentNullException();
			
			Delegate dlg = (Delegate)(object)handler;
			this.delegateRef = new SinglecastWeakDelegate(dlg);
			this.forwarder = WeakEventForwarderProvider.GetForwarder(dlg.Method);
		}
		
		public override bool Invoke(object sender, EventArgs e)
		{
			//if (!IsDisposed) if (_forwarder(_delegateRef.TargetReference, sender, e)) Dispose();
			
			var forwarder = this.forwarder;
			var delegateRef = this.delegateRef;

			if (forwarder != null && delegateRef != null) InnerInvoke(forwarder, delegateRef, sender, e);				
			
			return IsDisposed;
		}

		private void InnerInvoke(WeakEventForwarderProvider.ForwarderDelegate forwarder, SinglecastWeakDelegate delegateRef, object sender, EventArgs e)
		{
			bool shouldDispose;
			try
			{
				shouldDispose = forwarder(delegateRef.TargetReference, sender, e);
			} catch (Exception ex) {
				throw TweakedEventInvocationException.From(ex, delegateRef.TargetMethod);
			}

			if (shouldDispose) Dispose();
		}

		public override bool Equals(IEventEntry other)
		{
			var objOther = other as WeakEventEntry<TEH>;
			return (objOther == null) ? false : Equals(objOther);
		}
		
		public bool Equals(WeakEventEntry<TEH> other)
		{
			return delegateRef == other.delegateRef;
		}
		
		public override bool EqualsHandler(TEH handler)
		{
			//Cast handler to a Delegate
			Delegate dlg = (Delegate)(object)handler;
			
			return delegateRef.Equals(dlg);
		}

		public override void Dispose()
		{
			forwarder = null;
			delegateRef = null;
		}

		public override bool IsDisposed
		{
			get {
				var dlgRef = delegateRef;
				if (dlgRef != null && dlgRef.IsDead()) Dispose();

				return dlgRef == null;
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior) ThoughtWorks
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions