8000 Fix deadlock when shuting down · saaib/pythonnet@bf368fb · GitHub
[go: up one dir, main page]

Skip to content

Commit bf368fb

Browse files
Fix deadlock when shuting down
1 parent 385a5ed commit bf368fb

File tree

1 file changed

+22
-25
lines changed

1 file changed

+22
-25
lines changed

src/runtime/finalizer.cs

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,9 @@ public void Collect(bool forceDispose = true)
8080
if (Instance._finalizerTask != null
8181
&& !Instance._finalizerTask.IsCompleted)
8282
{
83-
using (Py.GIL())
84-
{
85-
var ts = PythonEngine.BeginAllowThreads();
86-
Instance._finalizerTask.Wait();
87-
PythonEngine.EndAllowThreads(ts);
88-
}
83+
var ts = PythonEngine.BeginAllowThreads();
84+
Instance._finalizerTask.Wait();
85+
PythonEngine.EndAllowThreads(ts);
8986
}
9087
else if (forceDispose)
9188
{
@@ -147,8 +144,11 @@ private void AddPendingCollect()
147144

148145
_finalizerTask = Task.Factory.StartNew(() =>
149146
{
150-
Instance.DisposeAll();
151-
_pending = false;
147+
using (Py.GIL())
148+
{
149+
Instance.DisposeAll();
150+
_pending = false;
151+
}
152152
});
153153
}
154154
}
@@ -169,27 +169,24 @@ private void DisposeAll()
169169
lock (_queueLock)
170170
#endif
171171
{
172-
using (Py.GIL())
173-
{
174172
#if FINALIZER_CHECK
175-
ValidateRefCount();
173+
ValidateRefCount();
176174
#endif
177-
IPyDisposable obj;
178-
while (_objQueue.TryDequeue(out obj))
175+
IPyDisposable obj;
176+
while (_objQueue.TryDequeue(out obj))
177+
{
178+
try
179179
{
180-
try
181-
{
182-
obj.Dispose();
183-
Runtime.CheckExceptionOccurred();
184-
}
185-
catch (Exception e)
180+
obj.Dispose();
181+
Runtime.CheckExceptionOccurred();
182+
}
183+
catch (Exception e)
184+
{
185+
// We should not bother the main thread
186+
ErrorHandler?.Invoke(this, new ErrorArgs()
186187
{
187-
// We should not bother the main thread
188-
ErrorHandler?.Invoke(this, new ErrorArgs()
189-
{
190-
Error = e
191-
});
192-
}
188+
Error = e
189+
});
193190
}
194191
}
195192
}

0 commit comments

Comments
 (0)
0