diff --git a/PLCSharpWpf/VVMs/Workflows/Workflow.cs b/PLCSharpWpf/VVMs/Workflows/Workflow.cs index 9f6bbe6..5f8788a 100644 --- a/PLCSharpWpf/VVMs/Workflows/Workflow.cs +++ b/PLCSharpWpf/VVMs/Workflows/Workflow.cs @@ -191,6 +191,8 @@ namespace PLCSharp.VVMs.Workflows private AssemblyCSharpBuilder AssemblyCSharpBuilder; + private NatashaLoadContext _loadContext; + private DelegateCommand _Compile; /// @@ -205,13 +207,26 @@ namespace PLCSharp.VVMs.Workflows { try { + if (IsRuning) + { + DebugLog += "正在运行中,请先停止后再编译。\n"; + return; + } Flow.Reset(); + // 卸载上一次编译的动态程序集域,避免每次编译的程序集永久驻留内存(无法被 GC 回收) + UnloadDomain(); + + // 新建可卸载的加载上下文(域),编译产物加载进该域,下次编译时可整体卸载 + _loadContext = NatashaManagement.CreateRandomDomain(); AssemblyCSharpBuilder = new(); + AssemblyCSharpBuilder.LoadContext = _loadContext; + // 新域没有 Preheating 预热的内存引用,合并主域(默认域)引用保证脚本能引用 PLCSharp 类型 + AssemblyCSharpBuilder.WithCombineReferences(item => item.UseAllReferences()); DebugLog = "编译中,请稍等。\n"; AssemblyCSharpBuilder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode()); AssemblyCSharpBuilder.Add(Code); - AssemblyCSharpBuilder.LogCompilationEvent += (log) => { DebugLog += log.ToString(); }; + AssemblyCSharpBuilder.LogCompilationEvent += OnCompilationLog; Assembly = AssemblyCSharpBuilder.GetAssembly(); DebugLog += "编译完成。\n"; @@ -232,11 +247,34 @@ namespace PLCSharp.VVMs.Workflows } catch (Exception e) { + IsCompiled = false; + Exception = true; DebugLog += e.Message; } } } + /// + /// 卸载动态程序集域 + /// + private void UnloadDomain() + { + // 先释放对旧程序集的所有强引用,否则 AssemblyLoadContext 无法真正卸载 + action = null; + Assembly = null; + AssemblyCSharpBuilder = null; + _loadContext?.Dispose(); + _loadContext = null; + } + + /// + /// 编译日志 + /// + private void OnCompilationLog(NatashaCompilationLog log) + { + DebugLog += log.ToString(); + } + private Action action; ///