@@ -179,15 +179,14 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
179
179
180
180
# You can't call AsyncToSync from a thread with a running event loop
181
181
try :
182
- event_loop = asyncio .get_running_loop ()
182
+ asyncio .get_running_loop ()
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,28 @@ 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
+ 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 :
236
249
# Make our own event loop - in a new thread - and run inside that.
237
250
loop_executor = ThreadPoolExecutor (max_workers = 1 )
238
251
loop_future = loop_executor .submit (asyncio .run , new_loop_wrap ())
239
252
# Run the CurrentThreadExecutor until the future is done.
240
253
current_executor .run_until_future (loop_future )
241
254
# Wait for future and/or allow for exception propagation
242
255
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
256
finally :
251
257
_restore_context (context [0 ])
252
258
# Restore old current thread executor state
0 commit comments