Vishal Saxena
Vishal Saxena

Reputation: 137

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: 

Upvotes: 0

Views: 921

Answers (2)

Hans Passant
Hans Passant

Reputation: 942328

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);
    }

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

It's because you are trying to use the cd variable inside the DomainUnload method and this variable is defined in the outside scope.

Upvotes: 0

Related Questions