Last active
June 23, 2018 20:56
-
-
Save neta1/836644d8875ff1a3221cc0ee2bd31484 to your computer and use it in GitHub Desktop.
Low Priority I/O @ PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using Microsoft.Win32.SafeHandles; | |
public static class PriorityHelper | |
{ | |
[DllImport("kernel32.dll", SetLastError = true)] | |
static extern SafeProcessHandle OpenProcess( | |
ProcessAccessFlags processAccess, | |
bool bInheritHandle, | |
int processId | |
); | |
[DllImport("ntdll.dll", SetLastError = true)] | |
static extern int NtSetInformationProcess(SafeProcessHandle processHandle, | |
PROCESS_INFORMATION_CLASS processInformationClass, IntPtr processInformation, | |
int processInformationLength); | |
[Flags] | |
enum ProcessAccessFlags : uint | |
{ | |
SetInformation = 0x00000200 | |
} | |
enum PROCESS_INFORMATION_CLASS : uint | |
{ | |
ProcessIoPriority = 33 // qs: ULONG | |
}; | |
const uint LowIoPriority = 1u; | |
public static bool SetLowPriorityIO(int procId) | |
{ | |
using (var hProc = OpenProcess(ProcessAccessFlags.SetInformation, false, procId)) | |
{ | |
if (hProc.IsInvalid) return false; | |
var ioPriority = IntPtr.Zero; | |
try | |
{ | |
var size = Marshal.SizeOf<uint>(); | |
ioPriority = Marshal.AllocHGlobal(size); | |
Marshal.WriteInt32(ioPriority, (int)LowIoPriority); | |
return NtSetInformationProcess(hProc, PROCESS_INFORMATION_CLASS.ProcessIoPriority, ioPriority, size) == 0; | |
} | |
finally | |
{ | |
if (ioPriority != IntPtr.Zero) Marshal.FreeHGlobal(ioPriority); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type @" | |
using System; | |
using System.Runtime.InteropServices; | |
(snip) | |
} | |
} | |
"@ | |
[PriorityHelper]::SetLowPriorityIO($PID) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment