Skip to content

Commit 327821b

Browse files
authored
Avoid using event_loop.is_running() (#507)
1 parent 719c46d commit 327821b

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

asgiref/sync.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -179,15 +179,14 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
179179

180180
# You can't call AsyncToSync from a thread with a running event loop
181181
try:
182-
event_loop = asyncio.get_running_loop()
182+
asyncio.get_running_loop()
183183
except RuntimeError:
184184
pass
185185
else:
186-
if event_loop.is_running():
187-
raise RuntimeError(
188-
"You cannot use AsyncToSync in the same thread as an async event loop - "
189-
"just await the async function directly."
190-
)
186+
raise RuntimeError(
187+
"You cannot use AsyncToSync in the same thread as an async event loop - "
188+
"just await the async function directly."
189+
)
191190

192191
# Make a future for the return information
193192
call_result: "Future[_R]" = Future()
@@ -232,21 +231,28 @@ async def new_loop_wrap() -> None:
232231
finally:
233232
del self.loop_thread_executors[loop]
234233

235-
if not (self.main_event_loop and self.main_event_loop.is_running()):
234+
if self.main_event_loop is not None:
235+
try:
236+
self.main_event_loop.call_soon_threadsafe(
237+
self.main_event_loop.create_task, awaitable
238+
)
239+
except RuntimeError:
240+
running_in_main_event_loop = False
241+
else:
242+
running_in_main_event_loop = True
243+
# Run the CurrentThreadExecutor until the future is done.
244+
current_executor.run_until_future(call_result)
245+
else:
246+
running_in_main_event_loop = False
247+
248+
if not running_in_main_event_loop:
236249
# Make our own event loop - in a new thread - and run inside that.
237250
loop_executor = ThreadPoolExecutor(max_workers=1)
238251
loop_future = loop_executor.submit(asyncio.run, new_loop_wrap())
239252
# Run the CurrentThreadExecutor until the future is done.
240253
current_executor.run_until_future(loop_future)
241254
# Wait for future and/or allow for exception propagation
242255
loop_future.result()
243-
else:
244-
# Call it inside the existing loop
245-
self.main_event_loop.call_soon_threadsafe(
246-
self.main_event_loop.create_task, awaitable
247-
)
248-
# Run the CurrentThreadExecutor until the future is done.
249-
current_executor.run_until_future(call_result)
250256
finally:
251257
_restore_context(context[0])
252258
# Restore old current thread executor state

0 commit comments

Comments
 (0)