Skip to content

Commit bacc7c0

Browse files
rking32delivrance
andauthored
Improve the async-to-sync wrapper (pyrogram#744)
* improved async to sync wrapper * Create a new loop in non-main threads & improve readability * Do not run_coroutine_threadsafe unless it's outside the loop Co-authored-by: Dan <14043624+delivrance@users.noreply.github.com>
1 parent e68da74 commit bacc7c0

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

pyrogram/sync.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,33 @@ def async_to_sync_wrap(*args, **kwargs):
4040
try:
4141
loop = asyncio.get_event_loop()
4242
except RuntimeError:
43-
loop = main_loop
43+
loop = asyncio.new_event_loop()
44+
asyncio.set_event_loop(loop)
4445

45-
if loop.is_running():
46-
if threading.current_thread() is threading.main_thread():
46+
if threading.current_thread() is threading.main_thread():
47+
if loop.is_running():
4748
return coroutine
4849
else:
4950
if inspect.iscoroutine(coroutine):
50-
return asyncio.run_coroutine_threadsafe(coroutine, loop).result()
51+
return loop.run_until_complete(coroutine)
5152

5253
if inspect.isasyncgen(coroutine):
53-
return asyncio.run_coroutine_threadsafe(consume_generator(coroutine), loop).result()
54-
55-
if inspect.iscoroutine(coroutine):
56-
return loop.run_until_complete(coroutine)
57-
58-
if inspect.isasyncgen(coroutine):
59-
return loop.run_until_complete(consume_generator(coroutine))
54+
return loop.run_until_complete(consume_generator(coroutine))
55+
else:
56+
if inspect.iscoroutine(coroutine):
57+
if loop.is_running():
58+
async def coro_wrapper():
59+
return await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(coroutine, main_loop))
60+
61+
return coro_wrapper()
62+
else:
63+
return asyncio.run_coroutine_threadsafe(coroutine, main_loop).result()
64+
65+
if inspect.isasyncgen(coroutine):
66+
if loop.is_running():
67+
return coroutine
68+
else:
69+
return asyncio.run_coroutine_threadsafe(consume_generator(coroutine), main_loop).result()
6070

6171
setattr(obj, name, async_to_sync_wrap)
6272

0 commit comments

Comments
 (0)