Is there a way to be notified (e.g. via an event or a callback) whenever a new ThreadPool thread is created?
I'm working on a .net console app that is using pjlib library via P/Invoke. This library requires that every thread that uses any of its APIs has to be previously registered via pj_thread_register API:
将外部或本机API创建的线程注册到PJLIB.必须在注册线程的上下文中调用此函数.当通过外部函数或API调用创建线程时,必须使用pj_thread_register()将其"注册"到PJLIB,以便与PJLIB的框架协作.在注册期间,需要维护一些数据,并且这些数据必须在线程的生命周期内保持可用.
当试图从未注册的线程调用任何pjlib函数时,该库确实会断言以下消息:
Calling pjlib from unknown/external thread. You must
register external threads with pj_thread_register()
before calling any pjlib functions.
现在,应用程序的业务逻辑使用async
和await
,作为一个控制台应用程序,SynchronizationContext为null,这意味着所有continuations都将在ThreadPool的线程上运行,包括对pjsip API的P/Invokes调用,这就需要在每次调用任何pjsip API之前调用pj_thread_register()
,确保新创建的线程池的线程在注册自己之前不会try 使用任何pjsip API.
我想,如果每当创建新线程池线程时,我都能收到通知(通过在新创建的线程上下文中调用的回调),我就可以使用这个回调只注册一次新线程.
或者,我可以在主线程或一些专用线程上使用SynchronizationContext(例如Stephen Cleary的AsyncContext或Stephen Toub的AsyncPump)(并在创建线程后立即注册),但这意味着要重新设计应用程序,可能要采用演员模型,有没有其他方法来应对这种情况?