February 26th, 2015

RegNotifyChangeKeyValue sucks less

One of the gotchas of the Reg­Notify­Change­Key­Value function is that the notification registration has thread affinity. This is a problem if you want the notification registration to outlive the thread that generated it. In particular, if you register the notification from a nonpersistent thread pool thread, you get into an infinite loop:

  1. Thread pool task calls Reg­Notify­Change­Key­Value, and waits for the associated event via Register­Wait­For­Single­Object.
  2. Thread pool thread goes idle.
  3. Thread pool destroys the idle thread.
  4. Due to thread affinity, this signals the handle.
  5. The thread pool queues a task to process the handle that was signaled.
  6. The task checks the registry key (observes that nothing changed) and calls Reg­Notify­Change­Key­Value again.
  7. Repeat.

Windows 8 added a new flag to the Reg­Notify­Change­Key­Value function: REG_NOTIFY_THREAD_AGNOSTIC. If you pass this flag, then the notification registration does not have thread affinity. If the thread that called Reg­Notify­Change­Key­Value exits, the notification registration remains active.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.