The following Pinvoke methods provide access to native functions required for job object management:
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr a, string lpName); [DllImport("kernel32.dll")] static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, UInt32 cbJobObjectInfoLength); [DllImport("kernel32.dll", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool CloseHandle(IntPtr hObject);
To create a job object, use CreateJobObject:
var handle = CreateJobObject(IntPtr.Zero, null);
To set information for the job object, use SetInformationJobObject:
var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION { LimitFlags = 0x2000 }; var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation = info }; int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)); IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length); Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false); if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length)) throw new Exception(string.Format("Unable to set information. Error: {0}", Marshal.GetLastWin32Error()));
To add a process to the job object, use AssignProcessToJobObject:
bool AddProcess(IntPtr processHandle) => AssignProcessToJobObject(handle, processHandle); bool AddProcess(int processId) => AddProcess(Process.GetProcessById(processId).Handle);
Dispose the job object using the custom Disposable implementation:
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposed) return; if (disposing) { } Close(); disposed = true; } public void Close() { CloseHandle(handle); handle = IntPtr.Zero; }
By utilizing this implementation, you can effectively create, configure, and manage job objects in your .NET applications.
The above is the detailed content of How to Manage Job Objects in .NET Using Pinvoke?. For more information, please follow other related articles on the PHP Chinese website!