Skip to content

Commit 5b36f47

Browse files
author
Christopher-Marcel Böddecker
authored
Fix/dispatch gc (#3)
* Pin dispatch functions to prevent GC on them. * Clear callback list on disposal of the Webview instance.
1 parent ba7bb31 commit 5b36f47

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

src/SharpWebview/Webview.cs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public class Webview : IDisposable
1515
{
1616
private bool _disposed = false;
1717
private List<CallBackFunction> callbacks = new List<CallBackFunction>();
18+
private List<DispatchFunction> dispatchFunctions = new List<DispatchFunction>();
1819

1920
private readonly IntPtr _nativeWebview;
2021

@@ -142,7 +143,21 @@ public void Evaluate(string javascript)
142143
/// <param name="dispatchFunc">The function to call on the main thread</param>
143144
public void Dispatch(Action dispatchFunc)
144145
{
145-
var dispatchFuncInstance = new DispatchFunction((_, __) => dispatchFunc());
146+
DispatchFunction dispatchFuncInstance = null!;
147+
dispatchFuncInstance = new DispatchFunction((_, __) =>
148+
{
149+
lock (dispatchFunctions)
150+
{
151+
dispatchFunctions.Remove(dispatchFuncInstance);
152+
}
153+
dispatchFunc();
154+
});
155+
156+
lock (dispatchFunctions)
157+
{
158+
dispatchFunctions.Add(dispatchFuncInstance); // Pin the callback for the GC
159+
}
160+
146161
Bindings.webview_dispatch(_nativeWebview, dispatchFuncInstance, IntPtr.Zero);
147162
}
148163

@@ -161,6 +176,13 @@ protected virtual void Dispose(bool disposing)
161176
{
162177
Bindings.webview_terminate(_nativeWebview);
163178
Bindings.webview_destroy(_nativeWebview);
179+
callbacks.Clear();
180+
181+
lock (dispatchFunctions)
182+
{
183+
dispatchFunctions.Clear();
184+
}
185+
164186
_disposed = true;
165187
}
166188
}

0 commit comments

Comments
 (0)