进程暂停

有的时候跑实验,CPU占用率非常的高。有的时候想收发邮件,聊个qq都不行。任务管理器里面也没有暂停进程的功能,我就想能么能自己开发一个暂停进程的功能。查找了Windows api没有发现有暂停进程的api,只找到了一个暂停线程的api。

 

上网找了一下资料发现code project上有一个类似的工具,做法是通过api找到一个进程下的所有线程,然后把进程的所有线程暂停,唤醒的时候就是把所有的线程唤醒。这样做可能有一个问题,就是有的线程已经暂停了,我们在唤醒的时候把原本是暂停的线程也唤醒了,这样很有可能破坏程序的逻辑。当然对于单线程程序来说,就不存在这样的问题。

 

下面是实现这个的核心代码:

复制代码
代码
BOOL CProcessManagerDlg::PauseResumeThreadList(DWORD dwOwnerPID, BOOL bResumeThread) 

    HANDLE        hThreadSnap 
= NULL; 
    BOOL          bRet        
= FALSE; 
    THREADENTRY32 te32        
= {0}; 
 
    
// Take a snapshot of all threads currently in the system. 

    hThreadSnap 
= CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); 
    
if (hThreadSnap == INVALID_HANDLE_VALUE) 
        
return (FALSE); 
 
    
// Fill in the size of the structure before using it. 

    te32.dwSize 
= sizeof(THREADENTRY32); 
 
    
// Walk the thread snapshot to find all threads of the process. 
    
// If the thread belongs to the process, add its information 
    
// to the display list.
 
    
if (Thread32First(hThreadSnap, &te32)) 
    { 
        
do 
        { 
            
if (te32.th32OwnerProcessID == dwOwnerPID) 
            {
                HANDLE hThread 
= OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID);
                
if (bResumeThread)
                {
                    ResumeThread(hThread);
                }
                
else
                {
                    SuspendThread(hThread);
                }
                CloseHandle(hThread);
            } 
        }
        
while (Thread32Next(hThreadSnap, &te32)); 
        bRet 
= TRUE; 
    } 
    
else 
        bRet 
= FALSE;          // could not walk the list of threads 
 
    
// Do not forget to clean up the snapshot object. 
    CloseHandle (hThreadSnap); 
 
    
return (bRet); 
}
复制代码

 

 最后为了实现一个简单的管理工具,我用MFC做了个界面,源代码点下载

posted on   小橋流水  阅读(475)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述

导航

统计

点击右上角即可分享
微信分享提示