c# - Do closures break serialization -
today faced serializationexception
refered anonymous inner class +<>c__displayclass10
stating not serializable, when iis tried store session in asp.net state service:
type 'xyz.generalunderstandingtests+aserializabletype+<>c__displayclass10' in assembly 'xyz, version=1.2.5429.24450, culture=neutral, publickeytoken=null' not marked serializable.
i looked lambdas in code , found quite few, of them not new , did never have issues in serialization. noticed had built in new lambda expression "happened" build closure.
searching stackoverflow closure serialization
found q&as reveal closures cannot serialized in other languages such php *) did not manage find such statement c#. have been able build simple example seems confirm closures not serializable whereas "normal" functions are
[testfixture] public class generalunderstandingtests { [serializable] private class aserializabletype { private readonly func<int> thisisaclosure; private readonly func<int> thisisnotaclosure; public aserializabletype() { const int someconst = 12345; thisisnotaclosure = () => someconst; // succeeds serialize var somevariable = 12345; thisisaclosure = () => somevariable; // fails serialize } } [test] public void aserializabletype_canbeserialized() { var sessionstateitemcollection = new system.web.sessionstate.sessionstateitemcollection(); sessionstateitemcollection["sut"] = new aserializabletype(); sessionstateitemcollection.serialize(new binarywriter(new memorystream())); } }
this test fails goes green line thisisaclosure = ...
commented out. line thisisnotaclosure = ...
not cause issues someconst
not variable constant, is, not build closure inlined compiler.
can confirm have concluded correct?
=> there way circumvent issue?
=> depends on internals of compiler used? since compiler turns lambda/closure expression anonymous inner class.
*) links:
Comments
Post a Comment