@@ -183,11 +183,10 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
183
183
except RuntimeError :
184
184
pass
185
185
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
+ )
191
190
192
191
# Make a future for the return information
193
192
call_result : "Future[_R]" = Future ()
@@ -232,21 +231,29 @@ async def new_loop_wrap() -> None:
232
231
finally :
233
232
del self .loop_thread_executors [loop ]
234
233
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 :
236
250
# Make our own event loop - in a new thread - and run inside that.
237
251
loop_executor = ThreadPoolExecutor (max_workers = 1 )
238
252
loop_future = loop_executor .submit (asyncio .run , new_loop_wrap ())
239
253
# Run the CurrentThreadExecutor until the future is done.
240
254
current_executor .run_until_future (loop_future )
241
255
# Wait for future and/or allow for exception propagation
242
256
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 )
250
257
finally :
251
258
_restore_context (context [0 ])
252
259
# Restore old current thread executor state
0 commit comments