diff --git a/PLCSharpWpf/VVMs/Workflows/Workflow.cs b/PLCSharpWpf/VVMs/Workflows/Workflow.cs index be8cd7f..5ef5cd2 100644 --- a/PLCSharpWpf/VVMs/Workflows/Workflow.cs +++ b/PLCSharpWpf/VVMs/Workflows/Workflow.cs @@ -243,24 +243,24 @@ namespace PLCSharp.VVMs.Workflows AssemblyCSharpBuilder.LogCompilationEvent += OnCompilationLog; Assembly = AssemblyCSharpBuilder.GetAssembly(); - DebugLog += "编译完成。\n"; - Prompt = ""; + var typeName = "Extension_" + ID.ToString("N"); + var extType = Assembly.GetTypes().FirstOrDefault(t => t.Name == typeName) + ?? throw new InvalidOperationException($"编译错误:无法找到 {typeName} 类型。"); + var run = extType.GetMethod("Run", BindingFlags.Public | BindingFlags.Instance, + null, [typeof(GlobalModel), typeof(FlowModel)], null) + ?? throw new InvalidOperationException("编译错误:无法绑定 Run(GlobalModel, FlowModel)。"); + // async void 在第一个 await 处返回,无法等待它退出再替换配方。 + if (run.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute), false)) + throw new InvalidOperationException("编译错误:Run 必须同步完成,无法等待异步脚本入口退出。"); + action = run.CreateDelegate>(Activator.CreateInstance(extType)); IsCompiled = true; Exception = false; - var typeName = "Extension_" + ID.ToString().Replace("-", ""); - var extType = Assembly.GetTypes().FirstOrDefault(t => t.Name == typeName || t.FullName == typeName); - if (extType != null) - { - var instance = Activator.CreateInstance(extType)!; - action = Assembly.GetDelegateFromShortName>(typeName, "Run", target: instance); - } - else - { - DebugLog += "编译错误:无法找到 Extension 类型。\n"; - } + Prompt = ""; + DebugLog += "编译完成。\n"; } catch (Exception e) { + UnloadDomain(); IsCompiled = false; Exception = true; DebugLog += e.Message; diff --git a/Tests/PLCSharp.Tests/WorkflowRegressionTests.cs b/Tests/PLCSharp.Tests/WorkflowRegressionTests.cs index 5e8e201..000d0a5 100644 --- a/Tests/PLCSharp.Tests/WorkflowRegressionTests.cs +++ b/Tests/PLCSharp.Tests/WorkflowRegressionTests.cs @@ -90,4 +90,24 @@ public class WorkflowRegressionTests File.Delete(path); } } + + [Theory] + [InlineData("public class Other {}")] + [InlineData("public class Extension_ID { public void Run() {} }")] + [InlineData("public class Extension_ID { public async void Run(PLCSharp.Models.GlobalModel model, PLCSharp.Core.Common.FlowModel flow) { await System.Threading.Tasks.Task.Yield(); } }")] + public void RecompileWithInvalidEntryClearsPreviousDelegate(string code) + { + var flow = Compile("public void Run(PLCSharp.Models.GlobalModel model, PLCSharp.Core.Common.FlowModel flow) { flow.Step++; }"); + Assert.True(flow.IsCompiled, flow.DebugLog); + flow.Run(null!); + Assert.Equal(1, flow.Flow.Step); + flow.Code = code.Replace("Extension_ID", $"Extension_{flow.ID:N}"); + flow.Compile.Execute(); + Assert.False(flow.IsCompiled); + Assert.True(flow.Exception); + Assert.Contains("编译错误", flow.DebugLog); + flow.Run(null!); + Assert.Equal(0, flow.Flow.Step); + Assert.False(flow.IsRuning); + } }