Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 376953
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T14:38:58+00:00 2026-05-12T14:38:58+00:00

UPDATE I have combined various answers from here into a ‘definitive’ answer on a

  • 0

UPDATE

I have combined various answers from here into a ‘definitive’ answer on a new question.

Original question

In my code I have an event publisher, which exists for the whole lifetime of the application (here reduced to bare essentials):

public class Publisher
{
    //ValueEventArgs<T> inherits from EventArgs
    public event EventHandler<ValueEventArgs<bool>> EnabledChanged; 
}

Because this publisher can be used all over the place, I was quite pleased with myself for creating this little helper class to avoid re-writing the handling code in all subscribers:

public static class Linker
{
    public static void Link(Publisher publisher, Control subscriber)
    {
         publisher.EnabledChanged += (s, e) => subscriber.Enabled = e.Value;
    }

    //(Non-lambda version, if you're not comfortable with lambdas)
    public static void Link(Publisher publisher, Control subscriber)
    {
         publisher.EnabledChanged +=
             delegate(object sender, ValueEventArgs<bool> e)
             {
                  subscriber.Enabled = e.Value;
             };
    }
}

It worked fine, until we started using it on smaller machines, when I started getting the occasional:

System.ComponentModel.Win32Exception
Not enough storage is available to process this command

As it turns out, there is one place in the code where subscribers controls are being dynamically created, added and removed from a form. Given my advanced understanding of garbage collection etc (i.e. none, until yesterday), I never thought to clear up behind me, as in the vast majority of cases, the subscribers also live for the lifetime of the application.

I’ve fiddled around a while with Dustin Campbell’s WeakEventHandler, but it doesn’t work with anonymous delegates (not for me anyway).

Is there anyway out of this problem? I really would like to avoid having to copy-paste boiler-plate code all over the shop.

(Oh, and don’t bother with asking me WHY we are creating and destroying controls all the time, it wasn’t my design decision…)

(PS: It’s a winforms application, but we’ve upgraded to VS2008 and .Net 3.5, should I consider using the Weak Event pattern?)

(PPS: Good answer from Rory, but if anyone can come up with an equivalent to the WeakEventHandler which avoids me having to remember to explicitly UnLink/Dispose, that would be cool…)

EDIT I must admit that I worked around this problem by “recycling” the controls in question. However the workaround has come back to haunt me as the ‘key’ I was using is apparently non-unique (sob). I’ve just discovered other links here (tried this – seems to be a bit too weak – GC clears delegates even if target is still alive, same problem with s,oɔɯǝɹ answer below), here (forces you to modify publisher, and doesn’t really work with anonymous delegates) and here (cited-as-incomplete by Dustin Campbell).

It occurs to me that what I’m looking for may be semantically impossible – closures are designed to ‘hang around even after I’m gone’.

I’ve found another workaround, so I’ll stick with that, pending a voice from the gods.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T14:38:58+00:00Added an answer on May 12, 2026 at 2:38 pm

    I know that this question is ancient, but hell – I found it, and I figure that others might as well. I’m trying to resolve a related issue, and might have some insight.

    You mentioned Dustin Campbell’s WeakEventHandler – it indeed cannot work with anonymous methods by design. I was trying to fiddle something together that would, when I realized that a) in 99% of cases I’d need something like this his original solution would be safer, and b) in those few cases where I have to (note: have to, not “want to because lambdas are so much prettier and concise”) it’s possible to make it work if you get a little clever.

    Your example seems like exactly the kind of one-off case where getting a little tricky can result in a fairly concise solution.

    
    public static class Linker {
        public static void Link(Publisher publisher, Control subscriber) {
            // anonymous method references the subscriber only through weak 
            // references,so its existance doesn't interfere with garbage collection
            var subscriber_weak_ref = new WeakReference(subscriber);
    
            // this instance variable will stay in memory as long as the  anonymous
            // method holds a reference to it we declare and initialize  it to 
            // reserve the memory (also,  compiler complains about uninitialized
            // variable otherwise)
            EventHandler<ValueEventArgs<bool>> handler = null;
    
            // when the handler is created it will grab references to the  local 
            // variables used within, keeping them in memory after the function 
            // scope ends
            handler = delegate(object sender, ValueEventArgs<bool> e) {
                var subscriber_strong_ref = subscriber_weak_ref.Target as Control;
    
                if (subscriber_strong_ref != null) 
                    subscriber_strong_ref.Enabled = e.Value;
                else {
                    // unsubscribing the delegate from within itself is risky, but
                    // because only one instance exists and nobody else has a
                    // reference to it we can do this
                    ((Publisher)sender).EnabledChanged -= handler;
    
                    // by assigning the original instance variable pointer to null
                    // we make sure that nothing else references the anonymous
                    // method and it can be collected. After this, the weak
                    //  reference and the handler pointer itselfwill be eligible for
                    // collection as well.
                    handler = null; 
                }
            };
    
            publisher.EnabledChanged += handler;
        }
    }
    

    The WPF Weak Event pattern is rumored to come with a lot of overhead, so in this particular situation I wouldn’t use it. Furthermore, referencing the core WPF library in a WinForm app seems a little heavy as well.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm programming in C here, for Windows and various Unix platforms. I have a
Q: If I have a composite key combined from 4 fields for example, can
I have update panel that content check box, textbox, 3 DropDownList with CascadingDropDown extender.
I have scenario, I have two update panels on the page (both have update
I have an UPDATE sql command that modifies a Date/Time field in a particular
I have some update or something that tries to run every night, and ends
I have an update query being run by a cron task that's timing out.
I have several update methods in a javascript file, used for updating my ajax
I have to update old projects at work. I do not have any experience
I have a update panel, in the update panel I have fileupload control and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.