How do I tell if an action is a lambda expression?

Posted by Keith on Stack Overflow See other posts from Stack Overflow or by Keith
Published on 2010-06-02T18:32:48Z Indexed on 2010/06/02 18:33 UTC
Read the original article Hit count: 298

I am using the EventAgregator pattern to subscribe and publish events. If a user subscribes to the event using a lambda expression, they must use a strong reference, not a weak reference, otherwise the expression can be garbage collected before the publish will execute.

I wanted to add a simple check in the DelegateReference so that if a programmer passes in a lambda expression and is using a weak reference, that I throw an argument exception. This is to help "police" the code.

Example:

eventAggregator.GetEvent<RuleScheduler.JobExecutedEvent>().Subscribe
        (
            e => resetEvent.Set(),
            ThreadOption.PublisherThread,
            false,
            // filter event, only interested in the job that this object started
            e => e.Value1.JobDetail.Name == jobName
        );


public DelegateReference(Delegate @delegate, bool keepReferenceAlive)
    {
        if (@delegate == null)
            throw new ArgumentNullException("delegate");

        if (keepReferenceAlive)
        {
            this._delegate = @delegate;
        }
        else
        {
            //TODO: throw exception if target is a lambda expression
            _weakReference = new WeakReference(@delegate.Target);
            _method = @delegate.Method;
            _delegateType = @delegate.GetType();
        }
    }

any ideas? I thought I could check for @delegate.Method.IsStatic but I don't believe that works... (is every lambda expression a static?)

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET