Skip to content

Memory leak in AppDomain.AssemblyResolve event subscription #630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 18, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 26 additions & 18 deletions src/Dotnet.Script.Core/ScriptRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,30 +34,38 @@ public async Task<TReturn> Execute<TReturn>(string dllPath, IEnumerable<string>
var runtimeDepsMap = ScriptCompiler.CreateScriptDependenciesMap(runtimeDeps);
var assembly = Assembly.LoadFrom(dllPath); // this needs to be called prior to 'AppDomain.CurrentDomain.AssemblyResolve' event handler added

AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => ResolveAssembly(args, runtimeDepsMap);
Assembly OnResolve(object sender, ResolveEventArgs args) => ResolveAssembly(args, runtimeDepsMap);

var type = assembly.GetType("Submission#0");
var method = type.GetMethod("<Factory>", BindingFlags.Static | BindingFlags.Public);

var globals = new CommandLineScriptGlobals(ScriptConsole.Out, CSharpObjectFormatter.Instance);
foreach (var arg in commandLineArgs)
globals.Args.Add(arg);

var submissionStates = new object[2];
submissionStates[0] = globals;

var resultTask = method.Invoke(null, new[] { submissionStates }) as Task<TReturn>;
AppDomain.CurrentDomain.AssemblyResolve += OnResolve;
try
{
_ = await resultTask;
var type = assembly.GetType("Submission#0");
var method = type.GetMethod("<Factory>", BindingFlags.Static | BindingFlags.Public);

var globals = new CommandLineScriptGlobals(ScriptConsole.Out, CSharpObjectFormatter.Instance);
foreach (var arg in commandLineArgs)
globals.Args.Add(arg);

var submissionStates = new object[2];
submissionStates[0] = globals;

var resultTask = method.Invoke(null, new[] { submissionStates }) as Task<TReturn>;
try
{
_ = await resultTask;
}
catch (System.Exception ex)
{
ScriptConsole.WriteError(ex.ToString());
throw new ScriptRuntimeException("Script execution resulted in an exception.", ex);
}

return await resultTask;
}
catch (System.Exception ex)
finally
{
ScriptConsole.WriteError(ex.ToString());
throw new ScriptRuntimeException("Script execution resulted in an exception.", ex);
AppDomain.CurrentDomain.AssemblyResolve -= OnResolve;
}

return await resultTask;
}

public Task<TReturn> Execute<TReturn>(ScriptContext context)
Expand Down