Cannot close a running event loop,when i call run_forever i can't close the loop

Question:

When i stop the websocket thread, i need loop thread stop either, but when i call loop.stop() and loop.close(),some trouble occurred,i can’t close the loop,some issue append, please help me, next it’s my code.
Please!Please!Please!Please!Please!Please!Please!Please!

def start_loop(loop): 
    """
    start anthor thread and start event loop, general, it's started with app together
    return a loop
    """
    try:
        asyncio.set_event_loop(loop)
        loop.run_forever()
    except Exception as e:
        logger.info(str(e))

        
this is funtion about create thread and run asyncio loop
def start_loop_thread():
    """_summary_
    start anthor thread and start event loop, general, it's started with app together
    return a loop
    Returns:
        Loop: a event loop
    """
    loop = asyncio.new_event_loop()
    t = threading.Thread(target=start_loop, args=(loop,))
    t.setDaemon(True)
    t.start()
    return loop


async def recv_message(websocket,channel,host_sys_name,command,recv_data_dict):
    while True:
        recv_ready = channel.recv_ready()
        print(f"recv_ready:{recv_ready}")
        if channel.recv_ready():
            recv_data = bytes_to_str(channel.recv(65535))
            recv_data_dict["recv"] = recv_data
            print(f"recvrecvrecv:{recv_data_dict}")
            if len(recv_data) != 0:
                await websocket.send_text(recv_data)
            if host_sys_name in recv_data:
                break
        else:
            if host_sys_name in recv_data_dict["recv"]:
                break
            if "r" in command:
                # time.sleep(5)
                continue
            else:
                break


@api_router.websocket("/{client_id}")
async def terminal_websocket_endpoint(websocket: WebSocket, server_info_depends:dict = Depends(get_server_info_depends)):
    await websocket.accept()
    if server_info_depends.get("code") == 1:
        await websocket.send_text(server_info_depends.get("message"))
        await websocket.close()
    loop = websocket.app.extra.get("loop",None)
    # if not loop:
    #     await websocket.send_text(server_info_depends.get("message"))
    #     await websocket.close()
    ip, port, username, password = server_info_depends.get("ip"),server_info_depends.get("port"),server_info_depends.get("username"),server_info_depends.get("password")
    # print(server_info_depends)
    ssh = NormalSshClient(ip=ip, port=port, username=username, password=base64_decode(password), websocket=websocket)
    ssh.connect()
    ssh.get_ssh_channel()
    time.sleep(0.1)
    host_sys_name = ""
    if ssh.channel:
        recv = bytes_to_str(ssh.channel.recv(2048))
        host_sys_name = get_host_system_name(recv)
        await websocket.send_text(recv)
    # start new thread
    loop = start_loop_thread()
    recv_data_dict = {"recv":""}
    # loop = asyncio.get_running_loop()
    try:
        while True:
            json_message = await websocket.receive()
            size = json_message.get("resize",None)
            if size and len(size)==2:
                try:
                    ssh.channel.resize_pty(*size)
                except Exception:
                    pass
            if json_message.get("code") == 1005:
                ssh.all_close()
                loop.stop()
                time.sleep(1)
                loop.close()
                return 0
            else:
                command = json_message.get("text")
                ssh.channel.send(command)
                # put coroutine in loop and running
                time.sleep(0.01)
                future = asyncio.run_coroutine_threadsafe(recv_message(websocket,ssh.channel,host_sys_name,command,recv_data_dict), loop)

    except Exception as e:
        print(e)
        
    finally:
        loop.stop()
        time.sleep(1)
        loop.close()

When i stop the websocket thread, i need loop thread stop either,but when i call loop.stop() and loop.close(),some trouble occurred

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesuvicornprotocolswebsocketswebsockets_impl.py", line 184, in run_asgi      
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesuvicornmiddlewareproxy_headers.py", line 78, in __call__
    return await self.app(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesfastapiapplications.py", line 269, in __call__
    await super().__call__(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletteapplications.py", line 124, in __call__
    await self.middleware_stack(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarlettemiddlewareerrors.py", line 149, in __call__
    await self.app(scope, receive, send)
  File "D:workspace2pythonfanhanprocess_v2fanhanprocess_v2configmiddleware.py", line 52, in __call__
    await self.app(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarlettemiddlewarecors.py", line 76, in __call__
    await self.app(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletteexceptions.py", line 69, in __call__
    await self.app(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesfastapimiddlewareasyncexitstack.py", line 21, in __call__
    raise e
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesfastapimiddlewareasyncexitstack.py", line 18, in __call__
    await self.app(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletterouting.py", line 670, in __call__
    await route.handle(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletterouting.py", line 325, in handle
    await self.app(scope, receive, send)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletterouting.py", line 81, in app
    await func(session)
  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesfastapirouting.py", line 279, in app
    await dependant.call(**values)
  File "D:workspace2pythonfanhanprocess_v2fanhanprocess_v2appsterminalws_view.py", line 91, in terminal_websocket_endpoint
    loop.close()
  File "D:softwarepythonan_3_10libasyncioproactor_events.py", line 677, in close
    raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
ERROR     2022-09-16 14:46:21.082 - uvicorn.protocols.websockets.websockets_impl:run_asgi - Exception in ASGI application
Traceback (most recent call last):

  File "D:softwarepythonan_3_10librunpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
           │         │     └ {'__name__': '__main__', '__doc__': None, '__package__': '', '__loader__': <_frozen_importlib_external.SourceFileLoader objec...
           │         └ <code object <module> at 0x000002057DEEC240, file "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFilesli...     
           └ <function _run_code at 0x000002057DEDB400>

  File "D:softwarepythonan_3_10librunpy.py", line 86, in _run_code
    exec(code, run_globals)
         │     └ {'__name__': '__main__', '__doc__': None, '__package__': '', '__loader__': <_frozen_importlib_external.SourceFileLoader objec...
         └ <code object <module> at 0x000002057DEEC240, file "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFilesli...

  File "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFileslibpythondebugpy__main__.py", line 39, in <module>
    cli.main()
    │   └ <function main at 0x0000020500C9E4D0>
    └ <module 'debugpy.server.cli' from 'c:\Users\fhxx\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\lib\python...

  File "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFileslibpythondebugpy/..debugpyservercli.py", line 430, in main
    run()
    └ <function run_file at 0x0000020500C9E290>

  File "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFileslibpythondebugpy/..debugpyservercli.py", line 284, in run_file
    runpy.run_path(target, run_name="__main__")
    │     │        └ 'D:\workspace2\python\fanhanprocess_v2\fanhanprocess_v2\main.py'
    │     └ <function run_path at 0x0000020500981750>
    └ <module '_pydevd_bundle.pydevd_runpy' from 'c:\Users\fhxx\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\li...

  File "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFileslibpythondebugpy_vendoredpydevd_pydevd_bundlepydevd_runpy.py", line 321, in run_path
    return _run_module_code(code, init_globals, run_name,
           │                │     │             └ '__main__'
           │                │     └ None
           │                └ <code object <module> at 0x0000020500CECB30, file "D:workspace2pythonfanhanprocess_v2fanhanprocess_v2main.py", line 1>   
           └ <function _run_module_code at 0x00000205009813F0>

  File "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFileslibpythondebugpy_vendoredpydevd_pydevd_bundlepydevd_runpy.py", line 135, in _run_module_code
    _run_code(code, mod_globals, init_globals,
    │         │     │            └ None
    │         │     └ {'__name__': '__main__', '__doc__': None, '__package__': '', '__loader__': None, '__spec__': None, '__file__': 'D:\workspace...      
    │         └ <code object <module> at 0x0000020500CECB30, file "D:workspace2pythonfanhanprocess_v2fanhanprocess_v2main.py", line 1>
    └ <function _run_code at 0x0000020500981000>

  File "c:Usersfhxx.vscodeextensionsms-python.python-2022.14.0pythonFileslibpythondebugpy_vendoredpydevd_pydevd_bundlepydevd_runpy.py", line 124, in _run_code
    exec(code, run_globals)
         │     └ {'__name__': '__main__', '__doc__': None, '__package__': '', '__loader__': None, '__spec__': None, '__file__': 'D:\workspace...
         └ <code object <module> at 0x0000020500CECB30, file "D:workspace2pythonfanhanprocess_v2fanhanprocess_v2main.py", line 1>

  File "D:workspace2pythonfanhanprocess_v2fanhanprocess_v2main.py", line 9, in <module>
    uvicorn.run("main:app", host="0.0.0.0", port=8000)
    │       └ <function run at 0x000002050196F370>
    └ <module 'uvicorn' from 'C:\Users\fhxx\.virtualenvs\fanhanprocess_v2-5XAg7VLT\lib\site-packages\uvicorn\__init__.py'>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesuvicornmain.py", line 575, in run
    server.run()
    │      └ <function Server.run at 0x000002050196EDD0>
    └ <uvicorn.server.Server object at 0x0000020504156F20>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesuvicornserver.py", line 60, in run
    return asyncio.run(self.serve(sockets=sockets))
           │       │   │    │             └ None
           │       │   │    └ <function Server.serve at 0x000002050196EE60>
           │       │   └ <uvicorn.server.Server object at 0x0000020504156F20>
           │       └ <function run at 0x0000020500DABBE0>
           └ <module 'asyncio' from 'D:\software\python\an_3_10\lib\asyncio\__init__.py'>

  File "D:softwarepythonan_3_10libasynciorunners.py", line 44, in run
    return loop.run_until_complete(main)
           │    │                  └ <coroutine object Server.serve at 0x000002050435C5F0>
           │    └ <function BaseEventLoop.run_until_complete at 0x0000020500DB5630>
           └ <ProactorEventLoop running=True closed=False debug=False>

  File "D:softwarepythonan_3_10libasynciobase_events.py", line 633, in run_until_complete
    self.run_forever()
    │    └ <function ProactorEventLoop.run_forever at 0x0000020501624430>
    └ <ProactorEventLoop running=True closed=False debug=False>

  File "D:softwarepythonan_3_10libasynciowindows_events.py", line 321, in run_forever
    super().run_forever()

  File "D:softwarepythonan_3_10libasynciobase_events.py", line 600, in run_forever
    self._run_once()
    │    └ <function BaseEventLoop._run_once at 0x0000020500DB70A0>
    └ <ProactorEventLoop running=True closed=False debug=False>

  File "D:softwarepythonan_3_10libasynciobase_events.py", line 1896, in _run_once
    handle._run()
    │      └ <function Handle._run at 0x0000020500D2A3B0>
    └ <Handle Task.task_wakeup(<Future finished result=None>)>

  File "D:softwarepythonan_3_10libasyncioevents.py", line 80, in _run
    self._context.run(self._callback, *self._args)
    │    │            │    │           │    └ <member '_args' of 'Handle' objects>
    │    │            │    │           └ <Handle Task.task_wakeup(<Future finished result=None>)>
    │    │            │    └ <member '_callback' of 'Handle' objects>
    │    │            └ <Handle Task.task_wakeup(<Future finished result=None>)>
    │    └ <member '_context' of 'Handle' objects>
    └ <Handle Task.task_wakeup(<Future finished result=None>)>

> File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesuvicornprotocolswebsocketswebsockets_impl.py", line 184, in run_asgi      
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
                   │    │   │    │      │    │             │    └ <function WebSocketProtocol.asgi_send at 0x0000020504428EE0>
                   │    │   │    │      │    │             └ <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000020504577A60>  
                   │    │   │    │      │    └ <function WebSocketProtocol.asgi_receive at 0x0000020504428F70>
                   │    │   │    │      └ <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000020504577A60>
                   │    │   │    └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...
                   │    │   └ <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000020504577A60>
                   │    └ <uvicorn.middleware.proxy_headers.ProxyHeadersMiddleware object at 0x0000020504329660>
                   └ <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000020504577A60>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesuvicornmiddlewareproxy_headers.py", line 78, in __call__
    return await self.app(scope, receive, send)
                 │    │   │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
                 │    │   │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
                 │    │   └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...
                 │    └ <fastapi.applications.FastAPI object at 0x0000020504329780>
                 └ <uvicorn.middleware.proxy_headers.ProxyHeadersMiddleware object at 0x0000020504329660>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesfastapiapplications.py", line 269, in __call__
    await super().__call__(scope, receive, send)
                           │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
                           │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
                           └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletteapplications.py", line 124, in __call__
    await self.middleware_stack(scope, receive, send)
          │    │                │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
          │    │                │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
          │    │                └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...
          │    └ <starlette.middleware.errors.ServerErrorMiddleware object at 0x00000205044EAAA0>
          └ <fastapi.applications.FastAPI object at 0x0000020504329780>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarlettemiddlewareerrors.py", line 149, in __call__
    await self.app(scope, receive, send)
          │    │   │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
          │    │   │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
          │    │   └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...       
          │    └ <config.middleware.CusAuthenticationMiddleware object at 0x00000205044EAA40>
          └ <starlette.middleware.errors.ServerErrorMiddleware object at 0x00000205044EAAA0>

  File "D:workspace2pythonfanhanprocess_v2fanhanprocess_v2configmiddleware.py", line 52, in __call__
    await self.app(scope, receive, send)
          │    │   │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
          │    │   │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
          │    │   └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...       
          │    └ <starlette.middleware.cors.CORSMiddleware object at 0x00000205044EA9B0>
          └ <config.middleware.CusAuthenticationMiddleware object at 0x00000205044EAA40>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarlettemiddlewarecors.py", line 76, in __call__
    await self.app(scope, receive, send)
          │    │   │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
          │    │   │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
          │    │   └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...       
          │    └ <starlette.exceptions.ExceptionMiddleware object at 0x00000205044EA860>
          └ <starlette.middleware.cors.CORSMiddleware object at 0x00000205044EA9B0>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletteexceptions.py", line 69, in __call__
    await self.app(scope, receive, send)
          │    │   │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
          │    │   │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
          │    │   └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...       
          │    └ <fastapi.middleware.asyncexitstack.AsyncExitStackMiddleware object at 0x00000205044EA7D0>
          └ <starlette.exceptions.ExceptionMiddleware object at 0x00000205044EA860>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesfastapimiddlewareasyncexitstack.py", line 21, in __call__
    raise e

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesfastapimiddlewareasyncexitstack.py", line 18, in __call__
    await self.app(scope, receive, send)
          │    │   │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
          │    │   │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
          │    │   └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...       
          │    └ <fastapi.routing.APIRouter object at 0x00000205043DF070>
          └ <fastapi.middleware.asyncexitstack.AsyncExitStackMiddleware object at 0x00000205044EA7D0>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletterouting.py", line 670, in __call__
    await route.handle(scope, receive, send)
          │     │      │      │        └ <bound method WebSocketProtocol.asgi_send of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0000...
          │     │      │      └ <bound method WebSocketProtocol.asgi_receive of <uvicorn.protocols.websockets.websockets_impl.WebSocketProtocol object at 0x0...
          │     │      └ {'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('1...   
          │     └ <function WebSocketRoute.handle at 0x0000020501F49FC0>
          └ <fastapi.routing.APIWebSocketRoute object at 0x0000020504477AC0>

  File "C:Usersfhxx.virtualenvsfanhanprocess_v2-5XAg7VLTlibsite-packagesstarletterouting.py", line 325, in handle
    await self.app(scope, receive, send)
INFO      2022-09-16 14:46:21.346 - config.middleware:__call__ - eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imx2eWl0YW8iLCJpZCI6NiwiZXhwIjoxNjYzMzEyNzY1fQ.BIG9rZkGpUKTrhWzjkx9gnZ254lVKTAzmsIeRJLnIEc
INFO      2022-09-16 14:46:21.379 - uvicorn.protocols.http.httptools_impl:send - 127.0.0.1:7263 - "GET /api/user/list HTTP/1.1" 200
INFO:     connection closed
INFO      2022-09-16 14:46:21.384 - websockets.legacy.server:handler - connection closed
INFO      2022-09-16 14:46:21.388 - uvicorn.protocols.http.httptools_impl:send - 127.0.0.1:7262 - "GET /favicon.ico HTTP/1.1" 200

this is test program,you guys can use it to test

import asyncio
import threading as tg
if __name__ == '__main__':
    def start_loop(loop):
        asyncio.set_event_loop(loop) # set loop
        loop.run_forever()
 
    async def do_some_work(x):
        print('Waiting {}'.format(x))
        await asyncio.sleep(x)
        print('Done after {}s'.format(x))
        return x
        
    new_loop = asyncio.new_event_loop()
    t = tg.Thread(target=start_loop, args=(new_loop,))
    t.daemon = 1
    t.start()
    print('begin')
    tasks=[]
    for s in [6,4]:
        tasks.append(asyncio.run_coroutine_threadsafe(do_some_work(s), new_loop))
    for task in tasks:print(task.result())   
    new_loop.stop()
    print('abc',tg.active_count())
    print('end')
    new_loop.close()
Asked By: kerwin_LV

||

Answers:

First get all task in loop and then cancel then and finally stop loop

pending = asyncio.all_tasks(loop=loop) 

for task in pending:
    task.cancel()
group = asyncio.gather(*pending, return_exceptions=True)
loop.run_until_complete(group) # wait for cancel errors complate
loop.close()

Answered By: PersianMan

I found a solution, add a async function:

async def stop():
    loop = asyncio.get_event_loop()
    loop.stop()

then execute the function in sub-thread:

    asyncio.run_coroutine_threadsafe(stop(), new_loop)

You will not see the same RuntimeError.

I think your code problem is that executing new_loop.stop() in main thread can’t affect the running event loop in sub-thread.

Answered By: Jedore
async def stop():
    loop = asyncio.get_event_loop()
    loop.stop()
    loop.close()
asyncio.run_coroutine_threadsafe(stop(), new_loop)

This is little additional remarks, and this is complete answer.
Thanks the other answers and helper.

Answered By: kerwin_LV
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.