匿名方法在访问本地变量时抛出运行时异常

时间:2010-12-16 14:44:21

标签: c# anonymous-methods

为什么以下代码会引发以下错误?

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: 

2 个答案:

答案 0 :(得分:3)

C#编译器生成一个不可见的助手类来实现lambda。您可以在异常消息<>c__DisplayClass3中看到其名称。由于lambda在添加的appdomain中运行,因此需要将此帮助程序类的实例从主域序列化到该appdomain。

这不起作用,这些辅助类没有[Serializable]属性。你不能在这里使用lambda,只需在静态辅助函数上使用常规事件赋值语法。像这样:

       cd.DomainUnload += NewAppDomain_DomainUnload;
    ...

    private static void NewAppDomain_DomainUnload(object sender, EventArgs e) {
        Console.WriteLine("AppDomain {0} unloading", AppDomain.CurrentDomain);
    }

答案 1 :(得分:0)

这是因为你试图在cd方法中使用DomainUnload变量,而这个变量是在外部范围内定义的。