CreateProcess 与 WaitForSingleObject 性能下降
每个人可能都知道运行程序并等待其结束的代码:
CreateProcess(...
WaitForSingleObject(Process.hProcess, INFINITE
我自己使用过几次。但最近我发现,当它启动具有多媒体播放功能的程序时,此调用的性能比从通用文件管理器(Windows XP)执行的相同进程差。我的(父)进程的 CPU 消耗没问题,但在播放片段时会出现意外的小停顿。
我做了一些改变,比如:
CreateProcess ...
do {
Sleep(100);
Res = WaitForSingleObject(Process.hProcess, 10);
} while (Res == WAIT_TIMEOUT);
这有帮助。现在子进程播放该片段没有问题。 那么第一个片段有什么问题,它是否记录在某处?正如我从测试中看到的,第二个“等待”比第一个“等待”更“放松”,但第一个至少在形式上不会占用 CPU
Everyone probably knows the code to run a program and wait for it to end:
CreateProcess(...
WaitForSingleObject(Process.hProcess, INFINITE
It was used several times by myself. But recently I found that this call when it launches a program with a multimedia playback has worse performance than the same process being executed from a general file manager (Windows XP). That's ok with CPU consumption of my (parent) process, but while playing the fragment there are unexpected little stops.
I made a little change to something like:
CreateProcess ...
do {
Sleep(100);
Res = WaitForSingleObject(Process.hProcess, 10);
} while (Res == WAIT_TIMEOUT);
And it helped. Now the child process plays the fragment without problems.
So what's wrong with the first fragment and is it documented somewhere? As I see from the tests the second "wait" is more "relaxed" than the first one, but the first one doesn't eat CPU at least formally
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果此代码在 UI 线程上运行,则会导致其他(直接或间接)向窗口发送消息的进程出现性能问题,因为在等待子进程时不会运行消息循环。 Sleep() 和 WaitForSingleObject() 将处理消息。
Windows 资源管理器(文件管理器)不会遇到此问题,因为它:
您可以调用 MsgWaitForMultipleObjects(),而不是调用 WaitForSingleObject() 。如果您为 dwWaitMask 参数指定 QS_ALLINPUT,则当您的事件发出信号或线程的消息队列中有输入时,MsgWaitForMultipleObjects 将返回。如果 MsgWaitForMultipleObjects() 由于消息可用而返回,您可以处理它并继续等待:
If this code is running on a UI thread, you will cause performance problems with other processes that (directly or indirectly) send messages to your window(s), since you do not run the message loop while you are waiting for the child process. Neither Sleep() nor WaitForSingleObject() will process messages.
Windows Explorer (the file manager) will not suffer this problem because it:
Instead of calling WaitForSingleObject(), you can call MsgWaitForMultipleObjects(). If you specifiy QS_ALLINPUT for the dwWaitMask parameter, MsgWaitForMultipleObjects will return either when your event is signaled or when there is input in the thread's message queue. If MsgWaitForMultipleObjects() returned because a message is available, you can process it and resume waiting: