以下 Pinvoke 方法提供对作业对象管理所需的本机函数的访问:
[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);
要创建作业对象,请使用 CreateJobObject:
var handle = CreateJobObject(IntPtr.Zero, null);
要设置作业对象的信息,请使用 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()));
添加进程处理作业对象,使用AssignProcessToJobObject:
bool AddProcess(IntPtr processHandle) => AssignProcessToJobObject(handle, processHandle); bool AddProcess(int processId) => AddProcess(Process.GetProcessById(processId).Handle);
使用自定义Disposable实现处置作业对象:
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; }
通过利用此实现后,您可以在 .NET 应用程序中有效地创建、配置和管理作业对象。
以上是如何使用 Pinvoke 管理 .NET 中的作业对象?的详细内容。更多信息请关注PHP中文网其他相关文章!