13
13
# limitations under the License.
14
14
15
15
16
- import asyncio
16
+ from asyncio import AbstractEventLoop , new_event_loop , run_coroutine_threadsafe
17
17
from threading import Thread
18
18
from typing import Any , Awaitable , Callable , Mapping , Optional , Union
19
19
@@ -29,7 +29,7 @@ class ToolboxSyncClient:
29
29
service endpoint.
30
30
"""
31
31
32
- __loop : Optional [asyncio . AbstractEventLoop ] = None
32
+ __loop : Optional [AbstractEventLoop ] = None
33
33
__thread : Optional [Thread ] = None
34
34
35
35
def __init__ (
@@ -49,7 +49,7 @@ def __init__(
49
49
# Running a loop in a background thread allows us to support async
50
50
# methods from non-async environments.
51
51
if self .__class__ .__loop is None :
52
- loop = asyncio . new_event_loop ()
52
+ loop = new_event_loop ()
53
53
thread = Thread (target = loop .run_forever , daemon = True )
54
54
thread .start ()
55
55
self .__class__ .__thread = thread
@@ -58,7 +58,7 @@ def __init__(
58
58
async def create_client ():
59
59
return ToolboxClient (url , client_headers = client_headers )
60
60
61
- self .__async_client = asyncio . run_coroutine_threadsafe (
61
+ self .__async_client = run_coroutine_threadsafe (
62
62
create_client (), self .__class__ .__loop
63
63
).result ()
64
64
@@ -67,8 +67,12 @@ def close(self):
67
67
Synchronously closes the underlying client session. Doing so will cause
68
68
any tools created by this Client to cease to function.
69
69
"""
70
- coro = self .__async_client .close ()
71
- asyncio .run_coroutine_threadsafe (coro , self .__loop ).result ()
70
+ if not self .__async_client .__session .closed :
71
+ coro = self .__async_client .close ()
72
+ run_coroutine_threadsafe (coro , self .__loop ).result ()
73
+
74
+ def __del__ (self ):
75
+ self .close ()
72
76
73
77
def load_tool (
74
78
self ,
@@ -104,7 +108,7 @@ def load_tool(
104
108
if not self .__loop or not self .__thread :
105
109
raise ValueError ("Background loop or thread cannot be None." )
106
110
107
- async_tool = asyncio . run_coroutine_threadsafe (coro , self .__loop ).result ()
111
+ async_tool = run_coroutine_threadsafe (coro , self .__loop ).result ()
108
112
return ToolboxSyncTool (async_tool , self .__loop , self .__thread )
109
113
110
114
def load_toolset (
@@ -147,7 +151,7 @@ def load_toolset(
147
151
if not self .__loop or not self .__thread :
148
152
raise ValueError ("Background loop or thread cannot be None." )
149
153
150
- async_tools = asyncio . run_coroutine_threadsafe (coro , self .__loop ).result ()
154
+ async_tools = run_coroutine_threadsafe (coro , self .__loop ).result ()
151
155
return [
152
156
ToolboxSyncTool (async_tool , self .__loop , self .__thread )
153
157
for async_tool in async_tools
0 commit comments