Skip to content

Commit a2886a5

Browse files
committed
avoid using is_running
1 parent 719c46d commit a2886a5

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

asgiref/sync.py

+20-13
Original file line numberDiff line numberDiff line change
@@ -183,11 +183,10 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
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,29 @@ 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+
235+
if self.main_event_loop is not None:
236+
try:
237+
self.main_event_loop.call_soon_threadsafe(
238+
self.main_event_loop.create_task, awaitable
239+
)
240+
except RuntimeError:
241+
running_in_main_event_loop = False
242+
else:
243+
running_in_main_event_loop = True
244+
# Run the CurrentThreadExecutor until the future is done.
245+
current_executor.run_until_future(call_result)
246+
else:
247+
running_in_main_event_loop = False
248+
249+
if not running_in_main_event_loop:
236250
# Make our own event loop - in a new thread - and run inside that.
237251
loop_executor = ThreadPoolExecutor(max_workers=1)
238252
loop_future = loop_executor.submit(asyncio.run, new_loop_wrap())
239253
# Run the CurrentThreadExecutor until the future is done.
240254
current_executor.run_until_future(loop_future)
241255
# Wait for future and/or allow for exception propagation
242256
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)
250257
finally:
251258
_restore_context(context[0])
252259
# Restore old current thread executor state

0 commit comments

Comments
 (0)