编译脚本时清理旧垃圾
This commit is contained in:
parent
05a65c62b9
commit
fae1fe3c36
@ -191,6 +191,8 @@ namespace PLCSharp.VVMs.Workflows
|
||||
|
||||
private AssemblyCSharpBuilder AssemblyCSharpBuilder;
|
||||
|
||||
private NatashaLoadContext _loadContext;
|
||||
|
||||
private DelegateCommand _Compile;
|
||||
|
||||
/// <summary>
|
||||
@ -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<object>());
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 卸载动态程序集域
|
||||
/// </summary>
|
||||
private void UnloadDomain()
|
||||
{
|
||||
// 先释放对旧程序集的所有强引用,否则 AssemblyLoadContext 无法真正卸载
|
||||
action = null;
|
||||
Assembly = null;
|
||||
AssemblyCSharpBuilder = null;
|
||||
_loadContext?.Dispose();
|
||||
_loadContext = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 编译日志
|
||||
/// </summary>
|
||||
private void OnCompilationLog(NatashaCompilationLog log)
|
||||
{
|
||||
DebugLog += log.ToString();
|
||||
}
|
||||
|
||||
private Action<GlobalModel, FlowModel> action;
|
||||
|
||||
/// <summary>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user