[en] The mystery of MiniChat in Zyan 2.4

Topics: Technical Support
Jan 23, 2013 at 10:45 AM
Edited Jan 23, 2013 at 10:32 PM

Hi everyone :)

I finally nailed down the bug that caused MiniChat to fire events incorrectly. I was never able to reproduce the bug on my machine which always seemed very strange to me because many folks noticed it.

It turned out that the bug was caused by closing over the loop variable. This issue was one of the breaking changes in C# v5 specification. I use C# v5 and Visual Studio 2012, that's why I wasn't able to reproduce the bug.

Have a look at this Reflector screenshot to see the compiler-generated code:

In C# 4, the loop variable is declared outside the loop. The callback will always use the same instance of the loop variable (class2.d) which causes indeterminancy. The value seen by the lambda-function depends on the time when this lambda is executed. Most of the time, all callbacks are executed when the loop is over, that's why all events are routed to the same client (the last value of the loop variable is used).

On the contrary, C# 5 version behaves as designed: every iteration of the loop creates a fresh copy of the loop variable to close over. That's why every callback accesses the correct value of the delegate.

I worked around this issue to make sure that C#4 builds of Zyan also work as expected. The workaround is straightforward: I copy loop variable to a new variable declared inside the loop body.

If you encounter this bug, please download the latest sources of Zyan and build it yourself. Of course, the upcoming release of Zyan will include the bugfix.

Jan 25, 2013 at 6:05 AM

Excellent work!