Gotcha: Don’t use anonymous delegates within loops

Okay, what do you think the following code prints?

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main(string[] args)
{
var strings = new string[] { "Hello ", "World" };
var actions = new List<Action>();
foreach (var s in strings)
{
actions.Add(() => Console.Write(s));
}
actions.ForEach(action => action());
}
}

If you think it says “WorldWorld”, you don’t really need to read the rest of this article.  You can skip to the section entitled “So you think you’re so smart”.

If, on the other hand, you think it prints “Hello World”, it’s worth explaining why the code doesn’t behave as expected.  The issue is the semantics of anonymous delegates.  Variables referenced within anonymous delegates are “live”.  If they change within the function, the latest value is used.  If they go out of scope, the last value is used.

The moral of this story is: don’t create a delegate in a loop, because it probably won’t do what you’re expecting.*  This bit me recently whilst trying to write code to stop a set of threads simultaneously.  The best option is to refactor the code and extract the line that adds in the action.  Of course, that gives you an ugly dialog box to deal with.

*Actually, any time the variable is changes before you use it, but loops are the most common case.

 

semantic-change

 

Actually, what the dialog is telling you is that extracting the method will result in the behaviour changing.  Luckily that’s what we actually want.  So, here you go, an even less elegant way to print “Hello World” on the console:

    static void Main(string[] args)
{
var strings = new string[] { "Hello ", "World" };
var actions = new List<Action>();
foreach (var s in strings)
{
AddAction(actions, s);
}
actions.ForEach(action => action());
}

private static void AddAction(List<Action> actions, string s)
{
actions.Add(() => Console.Write(s));
}

So you think you’re so smart

Okay, how about this code: 

    static void Main(string[] args)
{
var actions = from s in new string[] { "Hello ", "World" }
select new Action(() => Console.Write(s));
actions.ToList().ForEach(action => action());
}

If anyone can explain why this prints “Hello World” succinctly, there’s a beer in it.  The interesting things is that the “ToList” ensures that all of the actions are produced prior to execution, so it’s not to do with the co-routing aspect of Linq.  I believe it’s an example of why expressions of delegates and delegates are slightly different.  A more prosaic explanation would be simply to point out that Linq would be horribly broken if this didn’t behave.

Getting Started: How to Pause a Retlang Process Context

Well, in the words of Scott Hanselman “We’ll see how long this lasts.”.  Anyway, I should start as I mean to go on by providing some code that’s actually useful.

I’ve been using Mike Rettig‘s Retlang library a fair bit recently, and have nothing but praise for it.  I’ll go into more detail about why it’s great at a later date, but here I’ll just detail a problem that I encountered and how to solve it.

Let’s say that you’ve got a system that writes to the database and you need to bring the database down.  You need to stop your Retlang-using service from processing (or at least certain process contexts). 

Luckily, Retlang is a very well designed system with lots of injection points.  Here, we use the fact that each process context has an executor associated with it that actually processes the commands and we pause that.  There are the following design decisions worth understanding:

  • Retlang is heading increasingly towards a thread pool model, and that this code only works with the original “one thread per context” model.  If you used this in a thread pool model, it would not only pause the contexts you wanted to pause, but any contexts sharing the thread.
  • Batched commands are paused halfway through.  This behaviour is what I required, but it’s easy to change.
  • Existing running commands will complete.  This is desirable, since any process that could be paused mid-command could also be split into separate commands.
  • There’s no way to tell when the currently running commands complete.  This is unlikely to be a problem for you.

To use it, just create the context with this executor.  As you can see, the HaltingExecutor passes its commands onto an underlying executor.  This allows you to add logging or your own custom logic that you’ve already implemented.

using Retlang;
using System.Threading;

namespace ColourCoding.Parallel
{
public class HaltableExecutor : ICommandExecutor
{
ManualResetEvent _block = new ManualResetEvent(true);
ICommandExecutor _underlying;
bool _isHalted = false;

public HaltableExecutor()
{
_underlying = new Retlang.CommandExecutor();
}

public HaltableExecutor(ICommandExecutor underlying)
{
_underlying = underlying;
}

public void ExecuteAll(Command[] toExecute)
{
foreach (Command command in toExecute)
{
if (_block.WaitOne())
{
_underlying.ExecuteAll(new Command[] { command });
}
}
}

public void Halt()
{
lock (_block)
{
_isHalted = true;
_block.Reset();
}
}

public void Resume()
{
lock (_block)
{
_isHalted = false;
_block.Set();
}
}

public bool IsHalted
{
get
{
lock (_block)
{
return _isHalted;
}
}
}
}
}
Technorati Tags: ,