相关文章推荐
老实的火腿肠  ·  sql ...·  1 年前    · 
聪明的领带  ·  springboot jpa ...·  2 年前    · 

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Details

When I tried to call Python code working with asyncio from C#, it seems that executing asyncio.run_coroutine_threadsafe in another thread just got stuck with no error produced. Pythonnet works well with asyncio if loop is in the same thread.

Here is my code:

test.py

import asyncio
import threading
class FTController:
    def __init__(self):
        #creating a loop in a new thread
        self.loop = asyncio.new_event_loop()
        def f(loop):
            asyncio.set_event_loop(loop)
            loop.run_forever()
        t = threading.Thread(target=f, args=(self.loop,))
        t.start()
    @asyncio.coroutine
    def hello(self):
        print('hello')
        asyncio.sleep(1)
        print("Hello again!")
    def connectFT(self):
        print("connecting...")
        future = asyncio.run_coroutine_threadsafe(self.hello(), self.loop)
if __name__ == '__main__':
    ft = FTController()
    ft.connectFT()

Below is the C# code calling python code:

public void connect()
    using (Py.GIL())
         dynamic test = Py.Import("test");
         dynamic ftController = test.FTController();
         ftController.connect();
         Console.ReadKey();

It just got stuck in the line:
asyncio.run_coroutine_threadsafe(self.hello(), self.loop)

Thanks!

@zenchanhk not very familiar with async stuff, but have you tried calling BeginAllowThreads()? Some discussion here: