From 1bee87b2dae61e7b0e9c3c9f642ccea5891a2343 Mon Sep 17 00:00:00 2001 From: Christopher-Marcel Esser Date: Wed, 19 Oct 2022 12:18:53 +0200 Subject: [PATCH] Fix garbage collection of script callbacks on macOS. It seems like the `NSBlock` was garbage collected before the task completed. That's because the method elided the `async`/`await` keywords. For more information see https://blog.stephencleary.com/2016/12/eliding-async-await.html. --- Source/SpiderEye.Mac/CocoaWebview.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Source/SpiderEye.Mac/CocoaWebview.cs b/Source/SpiderEye.Mac/CocoaWebview.cs index 39f1ddc8..4df31dd8 100644 --- a/Source/SpiderEye.Mac/CocoaWebview.cs +++ b/Source/SpiderEye.Mac/CocoaWebview.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; @@ -105,10 +105,9 @@ public void LoadUri(Uri uri) ObjC.Call(Handle, "loadRequest:", request); } - public Task ExecuteScriptAsync(string script) + public async Task ExecuteScriptAsync(string script) { var taskResult = new TaskCompletionSource(); - NSBlock? block = null; ScriptEvalCallbackDelegate callback = (IntPtr self, IntPtr result, IntPtr error) => { @@ -126,17 +125,16 @@ public void LoadUri(Uri uri) } } catch (Exception ex) { taskResult.TrySetException(ex); } - finally { block!.Dispose(); } }; - block = new NSBlock(callback); + using NSBlock block = new NSBlock(callback); ObjC.Call( Handle, "evaluateJavaScript:completionHandler:", NSString.Create(script), block.Handle); - return taskResult.Task; + return await taskResult.Task; } public void Dispose()