ThreadPool的线程创建事件

ThreadPool's Thread creation event

有没有一种方法可以在创建新的 ThreadPool 线程时得到通知(例如,通过事件或回调)?
我正在开发一个使用 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:

的 .net 控制台应用程序

Register a thread that was created by external or native API to PJLIB. This function must be called in the context of the thread being registered. When the thread is created by external function or API call, it must be 'registered' to PJLIB using pj_thread_register(), so that it can cooperate with PJLIB's framework. During registration, some data needs to be maintained, and this data must remain available during the thread's lifetime.

当尝试从未注册的线程调用任何 pjlib 函数时,库确实会断言消息:

Calling pjlib from unknown/external thread. You must
register external threads with pj_thread_register()
before calling any pjlib functions.

现在,应用程序的业务逻辑使用 asyncawait,作为控制台应用程序,SynchronizationContext 为 null,这意味着所有延续都将 运行 在 ThreadPool 的线程上,包括P/Invokes 调用 pjsip APIs,因此有必要在每次调用任何 pjsip APIs 之前调用 pj_thread_register(),以确保新创建的 ThreadPool 的线程不会'在注册之前不要尝试使用任何 pjsip API。

我认为如果每当创建新的线程池线程时我都能收到通知(通过在新创建线程的上下文中调用的回调),我可以使用此回调仅注册一次新线程。 有没有办法接收这样的通知?

或者我可以在主线程或一些专用线程上使用 SynchronizationContext(例如 Stephen Cleary 的 AsyncContext or Stephen Toub's AsyncPump)(并在我创建它们后立即注册它们),但这意味着重新设计应用程序,也许转向演员模型,有没有其他方法来面对这种情况?

或许可以使用分析 API 或 ETW 来检测所有线程池创建事件。不过,我不确定由于这些事件,在该线程 的上下文中执行代码会有多容易。

我建议在互操作层中使用 [ThreadStatic] static bool PjInitialized; 字段,并对该层的每个调用添加检查。如果未初始化,则在实际调用之前调用 pj_thread_register