以下作業物件管理所需的本機函數的訪問:
[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中文網其他相關文章!