|
1 | 1 | import asyncio
|
| 2 | +import concurrent |
2 | 3 | import logging
|
3 | 4 | import platform
|
4 | 5 | from contextlib import suppress
|
|
48 | 49 | if platform.system() == "Windows":
|
49 | 50 | import threading
|
50 | 51 |
|
51 |
| - class Var: |
52 |
| - windows_loop = None |
53 |
| - windows_thread = None |
54 |
| - |
55 |
| - def windows_get_asyncio_event_loop(): |
56 |
| - if Var.windows_thread is None: |
57 |
| - if Var.windows_loop is None: |
58 |
| - Var.windows_loop = asyncio.WindowsProactorEventLoopPolicy().new_event_loop() |
59 |
| - asyncio.set_event_loop(Var.windows_loop) |
60 |
| - if not Var.windows_loop.is_running(): |
61 |
| - Var.windows_thread = threading.Thread( |
62 |
| - target=Var.windows_loop.run_forever, daemon=True |
63 |
| - ) |
64 |
| - Var.windows_thread.start() |
65 |
| - return Var.windows_loop |
66 |
| - |
67 |
| - async def windows_get_result(o): |
68 |
| - return asyncio.run_coroutine_threadsafe(o, windows_get_asyncio_event_loop()).result() |
69 |
| - |
70 |
| - def deferred_from_coro(o): |
| 52 | + class _WindowsAdapter: |
| 53 | + loop = None |
| 54 | + thread = None |
| 55 | + |
| 56 | + @classmethod |
| 57 | + def get_event_loop(cls) -> asyncio.AbstractEventLoop: |
| 58 | + if cls.thread is None: |
| 59 | + if cls.loop is None: |
| 60 | + policy = asyncio.WindowsProactorEventLoopPolicy() # type: ignore |
| 61 | + cls.loop = policy.new_event_loop() |
| 62 | + asyncio.set_event_loop(cls.loop) |
| 63 | + if not cls.loop.is_running(): |
| 64 | + cls.thread = threading.Thread(target=cls.loop.run_forever, daemon=True) |
| 65 | + cls.thread.start() |
| 66 | + return cls.loop |
| 67 | + |
| 68 | + @classmethod |
| 69 | + async def get_result(cls, o) -> concurrent.futures.Future: |
| 70 | + return asyncio.run_coroutine_threadsafe(coro=o, loop=cls.get_event_loop()).result() |
| 71 | + |
| 72 | + def deferred_from_coro(o) -> Deferred: |
71 | 73 | if isinstance(o, Deferred):
|
72 | 74 | return o
|
73 |
| - return deferred_from_coro_default(windows_get_result(o)) |
| 75 | + return deferred_from_coro_default(_WindowsAdapter.get_result(o)) |
74 | 76 |
|
75 | 77 | else:
|
76 | 78 | deferred_from_coro = deferred_from_coro_default
|
|
0 commit comments