简体   繁体   中英

GetWindowThreadProcessId Race condition Risk

Reading through the comments of another question , I see that there is risk of encountering race condition(s) when using the GetWindowThreadProcessId Windows API method. How big of a risk is this?

Allow me to provide background into what I am attempting. I am writing a timekeeping app in C# for my own personal use. My intent was to have the app detect (via Win API calls) when the active window has changed so that I can log time against the application being used. I have already located code that detects when the active window changes; now I am trying to determine the process associated with that window. I have located several posts on SO that point to GetWindowThreadProcessId as the solution, but as I mentioned there seems to be a potential issue in using it. If GetWindowThreadProcessId is not a safe way to go, then I am open to other alternatives.

My hope was to keep the code wholly in C#, but I am not (completely) opposed to moving parts of it into C/C++ if necessary.

Thanks!

The race is unavoidable. There's no API that can atomically do what you want.

But it's a rather benign race. What can go wrong? The window is closed just before you ask about it. So you get an error and then try again. All you need to do is be aware of the race condition and check for and handle errors gracefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM