The Ugliest Code I’ve Written in a While

  1. private EventHandler<MyEventArgs> NameObscured1(IMyForm form)

  2. {

  3.             return new EventHandler<NameObscured2>((sender, eventArgs) =>

  4. {

  5.                 form.TabControl.Enabled = false;

  6.                 IAsyncResult iar = null;

  7.                 Action bg = null;

  8.                 bg = new Action ( () => {

  9.                     NameObscured3((s) => {

  10.                         form.StatusLabel.Owner.Invoke(new Action(() => {

  11.                             form.StatusLabel.Text= s;

  12.                             form.StatusProgressBar.Value +=2;

  13. }));

  14.                         return false;

  15. });

  16.                     NameObscured4(sender, eventArgs);

  17. });

  18.                 Action enableForm = () => { form.TabControl.Enabled = true; form.StatusProgressBar.Value = 0; };

  19.                 AsyncCallback callback = (_) => { form.TabControl.Invoke(enableForm); bg.EndInvoke(iar); };

  20.                 iar  = bg.BeginInvoke(callback, null);

  21. });

  22. }

The question is… How can I make this more readable, and is it worth spending the time to do so?

Nesting lambdas to 4 deep cannot be a good idea, but honestly, factoring each one out to a method might actually make this code LESS readable IMO. In this case, it is just a damned shame that some things can be done cross threads in a Windows Forms application.

I’m guessing this is a sign that I am too tightly coupled and should have some kind of mediator which will then Invoke property updates on the correct thread, but I don’t have that now.

Moral of the story: don’t write nasty nested lambdas like me.