Anonymous Method throws runtime exception when accessing local variable
Why does the following code throw the following error?
private static void CreateNewAppDomain() {
var cd = AppDomain.CreateDomain("CustomDomain1");
cd.DomainUnload += (sender, args) => Console.WriteLine("Domain 0 unloading, sender{0}, args{1} domain {2}", sender, args,cd);
}
System.Runtime.Serialization.SerializationException was unhandled Message=Type 'CoreConstructs.AppDomainPlay+<>c__DisplayClass3' in assembly 'CoreConstructs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2642f93804f4bbd8' is not marked as serializable. Source=mscorlib
StackTrace:
at System.AppDomain.add_ProcessExit(EventHandler value)
at CoreConstructs.AppDomainPlay.CreateNewAppDomain() in C:\work\sampleCode\exploreCsharp\exploreCSharp\ParameterPassing\AppDomainPlay.cs:line 31
at CoreConstructs.AppDomainPlay.ExploreAppDomain() in C:\work\sampleCode\exploreCsharp\exploreCSharp\ParameterPassing\AppDomainPlay.cs:line 19
at CoreConstructs.Program.Main(String[] args) in C:\work\sampleCode\exploreCsharp\exploreCSharp\ParameterPassing\Program.cs:line 14
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain开发者_如何学编程.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
The C# compiler generates an invisible helper class to implement the lambda. You can see its name in the exception message, <>c__DisplayClass3
. Since the lambda runs in the added appdomain, the instance of this helper class needs to be serialized from the primary domain to that appdomain.
That cannot work, these helper classes don't have the [Serializable] attribute. You cannot use a lambda here, just use the regular event assignment syntax on a static helper function. Like this:
cd.DomainUnload += NewAppDomain_DomainUnload;
...
private static void NewAppDomain_DomainUnload(object sender, EventArgs e) {
Console.WriteLine("AppDomain {0} unloading", AppDomain.CurrentDomain);
}
It's because you are trying to use the cd
variable inside the DomainUnload
method and this variable is defined in the outside scope.
精彩评论