简体   繁体   English

GetWindowThreadProcessId竞争条件风险

[英]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. 通过阅读另一个问题的评论,我发现使用GetWindowThreadProcessId Windows API方法时存在遇到竞争条件的风险。 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. 我正在用C#编写一个计时应用程序供我个人使用。 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. 我的目的是让应用程序在活动窗口发生变化时检测(通过Win API调用),以便我可以记录正在使用的应用程序的时间。 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. 我在SO上找到了几个指向GetWindowThreadProcessId作为解决方案的帖子,但正如我所提到的,使用它似乎存在潜在的问题。 If GetWindowThreadProcessId is not a safe way to go, then I am open to other alternatives. 如果GetWindowThreadProcessId不是一种安全的方法,那么我愿意接受其他选择。

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. 我希望将代码完全保留在C#中,但我并不(完全)反对在必要时将其中的部分内容转换为C / C ++。

Thanks! 谢谢!

The race is unavoidable. 这场比赛是不可避免的。 There's no API that can atomically do what you want. 没有API可以原子地做你想要的。

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. 您需要做的就是了解竞争条件并优雅地检查和处理错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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