如何在C#中使用P/Invoke建立和管理作業物件以確保進程終止?
使用P/Invoke 實作CreateJobObject 和SetInformationJobObject 的範例
此範例示範如何建立作業物件(CreateJob資訊(SetInformationJobObject),以確保在作業執行時與作業關聯的程序終止
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace JobObjectPInvoke { class Program { const int JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000; [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 CloseHandle(IntPtr hObject); static void Main() { // Get a handle to the current process. IntPtr currentProcessHandle = Process.GetCurrentProcess().Handle; // Create a job object. IntPtr jobObjectHandle = CreateJobObject(IntPtr.Zero, null); if (jobObjectHandle == IntPtr.Zero) { throw new Exception($"Failed to create job object: {Marshal.GetLastWin32Error()}"); } // Set the limit information for the job object. JOBOBJECT_BASIC_LIMIT_INFORMATION jobLimitInfo = new JOBOBJECT_BASIC_LIMIT_INFORMATION { LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE }; int sizeOfJobLimitInfo = Marshal.SizeOf(jobLimitInfo); IntPtr ptrJobLimitInfo = Marshal.AllocHGlobal(sizeOfJobLimitInfo); Marshal.StructureToPtr(jobLimitInfo, ptrJobLimitInfo, false); if (!SetInformationJobObject(jobObjectHandle, JobObjectInfoType.BasicLimitInformation, ptrJobLimitInfo, (uint)sizeOfJobLimitInfo)) { throw new Exception($"Failed to set job limit information: {Marshal.GetLastWin32Error()}"); } // Add the current process to the job object. if (!AssignProcessToJobObject(jobObjectHandle, currentProcessHandle)) { throw new Exception($"Failed to add process to job object: {Marshal.GetLastWin32Error()}"); } // Sleep for 10 seconds. System.Threading.Thread.Sleep(10000); // Close the job object. CloseHandle(jobObjectHandle); // The current process will terminate when the job object is closed. You can use this example to create a sandbox environment for your processes. } #region Helper Classes [StructLayout(LayoutKind.Sequential)] struct JOBOBJECT_BASIC_LIMIT_INFORMATION { public Int64 PerProcessUserTimeLimit; public Int64 PerJobUserTimeLimit; public UInt32 LimitFlags; public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public UInt32 ActiveProcessLimit; public UIntPtr Affinity; public UInt32 PriorityClass; public UInt32 SchedulingClass; } public enum JobObjectInfoType { AssociateCompletionPortInformation = 7, BasicLimitInformation = 2, BasicUIRestrictions = 4, EndOfJobTimeInformation = 6, ExtendedLimitInformation = 9, SecurityLimitInformation = 5 } #endregion } }
這個擴充範例說明了建立作業物件、設定其基本限制資訊以及向作業物件新增流程的完整實作。 JOBOBJECT_LIMIT_KILL_ON_JOB_CLOSE 標誌確保當作業物件關閉時,與作業關聯的任何進程都會被終止,從而確保進程使用的所有資源都被正確清理。
以上是如何在C#中使用P/Invoke建立和管理作業物件以確保進程終止?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

C#和C 的歷史與演變各有特色,未來前景也不同。 1.C 由BjarneStroustrup在1983年發明,旨在將面向對象編程引入C語言,其演變歷程包括多次標準化,如C 11引入auto關鍵字和lambda表達式,C 20引入概念和協程,未來將專注於性能和系統級編程。 2.C#由微軟在2000年發布,結合C 和Java的優點,其演變注重簡潔性和生產力,如C#2.0引入泛型,C#5.0引入異步編程,未來將專注於開發者的生產力和雲計算。

C 持續使用的理由包括其高性能、廣泛應用和不斷演進的特性。 1)高效性能:通過直接操作內存和硬件,C 在系統編程和高性能計算中表現出色。 2)廣泛應用:在遊戲開發、嵌入式系統等領域大放異彩。 3)不斷演進:自1983年發布以來,C 持續增加新特性,保持其競爭力。

C#和C 的学习曲线和开发者体验有显著差异。1)C#的学习曲线较平缓,适合快速开发和企业级应用。2)C 的学习曲线较陡峭,适用于高性能和低级控制的场景。

C 通過第三方庫(如TinyXML、Pugixml、Xerces-C )與XML交互。 1)使用庫解析XML文件,將其轉換為C 可處理的數據結構。 2)生成XML時,將C 數據結構轉換為XML格式。 3)在實際應用中,XML常用於配置文件和數據交換,提升開發效率。

C 學習者和開發者可以從StackOverflow、Reddit的r/cpp社區、Coursera和edX的課程、GitHub上的開源項目、專業諮詢服務以及CppCon等會議中獲得資源和支持。 1.StackOverflow提供技術問題的解答;2.Reddit的r/cpp社區分享最新資訊;3.Coursera和edX提供正式的C 課程;4.GitHub上的開源項目如LLVM和Boost提陞技能;5.專業諮詢服務如JetBrains和Perforce提供技術支持;6.CppCon等會議有助於職業

C 在現代編程中仍然具有重要相關性。 1)高性能和硬件直接操作能力使其在遊戲開發、嵌入式系統和高性能計算等領域佔據首選地位。 2)豐富的編程範式和現代特性如智能指針和模板編程增強了其靈活性和效率,儘管學習曲線陡峭,但其強大功能使其在今天的編程生態中依然重要。

C 的未來將專注於並行計算、安全性、模塊化和AI/機器學習領域:1)並行計算將通過協程等特性得到增強;2)安全性將通過更嚴格的類型檢查和內存管理機制提升;3)模塊化將簡化代碼組織和編譯;4)AI和機器學習將促使C 適應新需求,如數值計算和GPU編程支持。

1)c relevantduetoItsAverity and效率和效果臨界。 2)theLanguageIsconTinuellyUped,withc 20introducingFeaturesFeaturesLikeTuresLikeSlikeModeLeslikeMeSandIntIneStoImproutiMimproutimprouteverusabilityandperformance.3)
