Code:
/ Dotnetfx_Win7_3.5.1 / Dotnetfx_Win7_3.5.1 / 3.5.1 / DEVDIV / depot / DevDiv / releases / whidbey / NetFXspW7 / ndp / fx / src / Services / Monitoring / system / Diagnosticts / ProcessThread.cs / 1 / ProcessThread.cs
//------------------------------------------------------------------------------ //// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------------- namespace System.Diagnostics { using System.Threading; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Collections; using System.IO; using Microsoft.Win32; using System.Security.Permissions; using Microsoft.Win32.SafeHandles; // using System.Windows.Forms; ////// [ Designer("System.Diagnostics.Design.ProcessThreadDesigner, " + AssemblyRef.SystemDesign), HostProtection(SelfAffectingProcessMgmt=true, SelfAffectingThreading=true) ] public class ProcessThread : Component { // // FIELDS // ThreadInfo threadInfo; bool isRemoteMachine; bool priorityBoostEnabled; bool havePriorityBoostEnabled; ThreadPriorityLevel priorityLevel; bool havePriorityLevel; // // CONSTRUCTORS // ////// Represents a Win32 thread. This can be used to obtain /// information about the thread, such as it's performance characteristics. This is /// returned from the System.Diagnostics.Process.ProcessThread property of the System.Diagnostics.Process component. /// ////// I don't understand /// the following comment associated with the previous sentence: "property of /// Process component " Rather than just "processTHread". There is no such /// member on Process. Do we mean 'threads'? /// ////// Internal constructor. /// ///internal ProcessThread(bool isRemoteMachine, ThreadInfo threadInfo) { this.isRemoteMachine = isRemoteMachine; this.threadInfo = threadInfo; GC.SuppressFinalize(this); } // // PROPERTIES // /// /// Returns the base priority of the thread which is computed by combining the /// process priority class with the priority level of the associated thread. /// [MonitoringDescription(SR.ThreadBasePriority)] public int BasePriority { get { return threadInfo.basePriority; } } ////// The current priority indicates the actual priority of the associated thread, /// which may deviate from the base priority based on how the OS is currently /// scheduling the thread. /// [MonitoringDescription(SR.ThreadCurrentPriority)] public int CurrentPriority { get { return threadInfo.currentPriority; } } ////// Returns the unique identifier for the associated thread. /// [MonitoringDescription(SR.ThreadId)] public int Id { get { return threadInfo.threadId; } } ////// [Browsable(false)] public int IdealProcessor { set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION); if (NativeMethods.SetThreadIdealProcessor(threadHandle, value) < 0) { throw new Win32Exception(); } } finally { CloseThreadHandle(threadHandle); } } } ////// Sets the processor that this thread would ideally like to run on. /// ////// Returns or sets whether this thread would like a priority boost if the user interacts /// with user interface associated with this thread. /// [MonitoringDescription(SR.ThreadPriorityBoostEnabled)] public bool PriorityBoostEnabled { get { if (!havePriorityBoostEnabled) { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_QUERY_INFORMATION); bool disabled = false; if (!NativeMethods.GetThreadPriorityBoost(threadHandle, out disabled)) { throw new Win32Exception(); } priorityBoostEnabled = !disabled; havePriorityBoostEnabled = true; } finally { CloseThreadHandle(threadHandle); } } return priorityBoostEnabled; } set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION); if (!NativeMethods.SetThreadPriorityBoost(threadHandle, !value)) throw new Win32Exception(); priorityBoostEnabled = value; havePriorityBoostEnabled = true; } finally { CloseThreadHandle(threadHandle); } } } ////// Returns or sets the priority level of the associated thread. The priority level is /// not an absolute level, but instead contributes to the actual thread priority by /// considering the priority class of the process. /// [MonitoringDescription(SR.ThreadPriorityLevel)] public ThreadPriorityLevel PriorityLevel { get { if (!havePriorityLevel) { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_QUERY_INFORMATION); int value = NativeMethods.GetThreadPriority(threadHandle); if (value == 0x7fffffff) { throw new Win32Exception(); } priorityLevel = (ThreadPriorityLevel)value; havePriorityLevel = true; } finally { CloseThreadHandle(threadHandle); } } return priorityLevel; } set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION); if (!NativeMethods.SetThreadPriority(threadHandle, (int)value)) { throw new Win32Exception(); } priorityLevel = value; } finally { CloseThreadHandle(threadHandle); } } } ////// Returns the amount of time the thread has spent running code inside the operating /// system core. /// [MonitoringDescription(SR.ThreadPrivilegedProcessorTime)] public TimeSpan PrivilegedProcessorTime { get { EnsureState(State.IsNt); return GetThreadTimes().PrivilegedProcessorTime; } } ////// Returns the memory address of the function that was called when the associated /// thread was started. /// [MonitoringDescription(SR.ThreadStartAddress)] public IntPtr StartAddress { get { EnsureState(State.IsNt); return threadInfo.startAddress; } } ////// Returns the time the associated thread was started. /// [MonitoringDescription(SR.ThreadStartTime)] public DateTime StartTime { get { EnsureState(State.IsNt); return GetThreadTimes().StartTime; } } ////// Returns the current state of the associated thread, e.g. is it running, waiting, etc. /// [MonitoringDescription(SR.ThreadThreadState)] public ThreadState ThreadState { get { EnsureState(State.IsNt); return threadInfo.threadState; } } ////// Returns the amount of time the associated thread has spent utilizing the CPU. /// It is the sum of the System.Diagnostics.ProcessThread.UserProcessorTime and /// System.Diagnostics.ProcessThread.PrivilegedProcessorTime. /// [MonitoringDescription(SR.ThreadTotalProcessorTime)] public TimeSpan TotalProcessorTime { get { EnsureState(State.IsNt); return GetThreadTimes().TotalProcessorTime; } } ////// Returns the amount of time the associated thread has spent running code /// inside the application (not the operating system core). /// [MonitoringDescription(SR.ThreadUserProcessorTime)] public TimeSpan UserProcessorTime { get { EnsureState(State.IsNt); return GetThreadTimes().UserProcessorTime; } } ////// Returns the reason the associated thread is waiting, if any. /// [MonitoringDescription(SR.ThreadWaitReason)] public ThreadWaitReason WaitReason { get { EnsureState(State.IsNt); if (threadInfo.threadState != ThreadState.Wait) { throw new InvalidOperationException(SR.GetString(SR.WaitReasonUnavailable)); } return threadInfo.threadWaitReason; } } // // METHODS // ////// Helper to close a thread handle. /// ///private static void CloseThreadHandle(SafeThreadHandle handle) { if (handle != null) { handle.Close(); } } /// /// Helper to check preconditions for property access. /// void EnsureState(State state) { if ( ((state & State.IsLocal) != (State)0) && isRemoteMachine) { throw new NotSupportedException(SR.GetString(SR.NotSupportedRemoteThread)); } if ((state & State.IsNt) != (State)0) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired)); } } } ////// Helper to open a thread handle. /// ///SafeThreadHandle OpenThreadHandle(int access) { EnsureState(State.IsLocal); return ProcessManager.OpenThread(threadInfo.threadId, access); } /// /// Resets the ideal processor so there is no ideal processor for this thread (e.g. /// any processor is ideal). /// public void ResetIdealProcessor() { // 32 means "any processor is fine" IdealProcessor = 32; } ////// Sets which processors the associated thread is allowed to be scheduled to run on. /// Each processor is represented as a bit: bit 0 is processor one, bit 1 is processor /// two, etc. For example, the value 1 means run on processor one, 2 means run on /// processor two, 3 means run on processor one or two. /// [Browsable(false)] public IntPtr ProcessorAffinity { set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION | NativeMethods.THREAD_QUERY_INFORMATION); if (NativeMethods.SetThreadAffinityMask(threadHandle, new HandleRef(this, value)) == IntPtr.Zero) { throw new Win32Exception(); } } finally { CloseThreadHandle(threadHandle); } } } private ProcessThreadTimes GetThreadTimes() { ProcessThreadTimes threadTimes = new ProcessThreadTimes(); SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_QUERY_INFORMATION); if (!NativeMethods.GetThreadTimes(threadHandle, out threadTimes.create, out threadTimes.exit, out threadTimes.kernel, out threadTimes.user)) { throw new Win32Exception(); } } finally { CloseThreadHandle(threadHandle); } return threadTimes; } ////// Preconditions for accessing properties. /// ///enum State { IsLocal = 0x2, IsNt = 0x4 } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------------- namespace System.Diagnostics { using System.Threading; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Collections; using System.IO; using Microsoft.Win32; using System.Security.Permissions; using Microsoft.Win32.SafeHandles; // using System.Windows.Forms; ////// [ Designer("System.Diagnostics.Design.ProcessThreadDesigner, " + AssemblyRef.SystemDesign), HostProtection(SelfAffectingProcessMgmt=true, SelfAffectingThreading=true) ] public class ProcessThread : Component { // // FIELDS // ThreadInfo threadInfo; bool isRemoteMachine; bool priorityBoostEnabled; bool havePriorityBoostEnabled; ThreadPriorityLevel priorityLevel; bool havePriorityLevel; // // CONSTRUCTORS // ////// Represents a Win32 thread. This can be used to obtain /// information about the thread, such as it's performance characteristics. This is /// returned from the System.Diagnostics.Process.ProcessThread property of the System.Diagnostics.Process component. /// ////// I don't understand /// the following comment associated with the previous sentence: "property of /// Process component " Rather than just "processTHread". There is no such /// member on Process. Do we mean 'threads'? /// ////// Internal constructor. /// ///internal ProcessThread(bool isRemoteMachine, ThreadInfo threadInfo) { this.isRemoteMachine = isRemoteMachine; this.threadInfo = threadInfo; GC.SuppressFinalize(this); } // // PROPERTIES // /// /// Returns the base priority of the thread which is computed by combining the /// process priority class with the priority level of the associated thread. /// [MonitoringDescription(SR.ThreadBasePriority)] public int BasePriority { get { return threadInfo.basePriority; } } ////// The current priority indicates the actual priority of the associated thread, /// which may deviate from the base priority based on how the OS is currently /// scheduling the thread. /// [MonitoringDescription(SR.ThreadCurrentPriority)] public int CurrentPriority { get { return threadInfo.currentPriority; } } ////// Returns the unique identifier for the associated thread. /// [MonitoringDescription(SR.ThreadId)] public int Id { get { return threadInfo.threadId; } } ////// [Browsable(false)] public int IdealProcessor { set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION); if (NativeMethods.SetThreadIdealProcessor(threadHandle, value) < 0) { throw new Win32Exception(); } } finally { CloseThreadHandle(threadHandle); } } } ////// Sets the processor that this thread would ideally like to run on. /// ////// Returns or sets whether this thread would like a priority boost if the user interacts /// with user interface associated with this thread. /// [MonitoringDescription(SR.ThreadPriorityBoostEnabled)] public bool PriorityBoostEnabled { get { if (!havePriorityBoostEnabled) { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_QUERY_INFORMATION); bool disabled = false; if (!NativeMethods.GetThreadPriorityBoost(threadHandle, out disabled)) { throw new Win32Exception(); } priorityBoostEnabled = !disabled; havePriorityBoostEnabled = true; } finally { CloseThreadHandle(threadHandle); } } return priorityBoostEnabled; } set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION); if (!NativeMethods.SetThreadPriorityBoost(threadHandle, !value)) throw new Win32Exception(); priorityBoostEnabled = value; havePriorityBoostEnabled = true; } finally { CloseThreadHandle(threadHandle); } } } ////// Returns or sets the priority level of the associated thread. The priority level is /// not an absolute level, but instead contributes to the actual thread priority by /// considering the priority class of the process. /// [MonitoringDescription(SR.ThreadPriorityLevel)] public ThreadPriorityLevel PriorityLevel { get { if (!havePriorityLevel) { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_QUERY_INFORMATION); int value = NativeMethods.GetThreadPriority(threadHandle); if (value == 0x7fffffff) { throw new Win32Exception(); } priorityLevel = (ThreadPriorityLevel)value; havePriorityLevel = true; } finally { CloseThreadHandle(threadHandle); } } return priorityLevel; } set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION); if (!NativeMethods.SetThreadPriority(threadHandle, (int)value)) { throw new Win32Exception(); } priorityLevel = value; } finally { CloseThreadHandle(threadHandle); } } } ////// Returns the amount of time the thread has spent running code inside the operating /// system core. /// [MonitoringDescription(SR.ThreadPrivilegedProcessorTime)] public TimeSpan PrivilegedProcessorTime { get { EnsureState(State.IsNt); return GetThreadTimes().PrivilegedProcessorTime; } } ////// Returns the memory address of the function that was called when the associated /// thread was started. /// [MonitoringDescription(SR.ThreadStartAddress)] public IntPtr StartAddress { get { EnsureState(State.IsNt); return threadInfo.startAddress; } } ////// Returns the time the associated thread was started. /// [MonitoringDescription(SR.ThreadStartTime)] public DateTime StartTime { get { EnsureState(State.IsNt); return GetThreadTimes().StartTime; } } ////// Returns the current state of the associated thread, e.g. is it running, waiting, etc. /// [MonitoringDescription(SR.ThreadThreadState)] public ThreadState ThreadState { get { EnsureState(State.IsNt); return threadInfo.threadState; } } ////// Returns the amount of time the associated thread has spent utilizing the CPU. /// It is the sum of the System.Diagnostics.ProcessThread.UserProcessorTime and /// System.Diagnostics.ProcessThread.PrivilegedProcessorTime. /// [MonitoringDescription(SR.ThreadTotalProcessorTime)] public TimeSpan TotalProcessorTime { get { EnsureState(State.IsNt); return GetThreadTimes().TotalProcessorTime; } } ////// Returns the amount of time the associated thread has spent running code /// inside the application (not the operating system core). /// [MonitoringDescription(SR.ThreadUserProcessorTime)] public TimeSpan UserProcessorTime { get { EnsureState(State.IsNt); return GetThreadTimes().UserProcessorTime; } } ////// Returns the reason the associated thread is waiting, if any. /// [MonitoringDescription(SR.ThreadWaitReason)] public ThreadWaitReason WaitReason { get { EnsureState(State.IsNt); if (threadInfo.threadState != ThreadState.Wait) { throw new InvalidOperationException(SR.GetString(SR.WaitReasonUnavailable)); } return threadInfo.threadWaitReason; } } // // METHODS // ////// Helper to close a thread handle. /// ///private static void CloseThreadHandle(SafeThreadHandle handle) { if (handle != null) { handle.Close(); } } /// /// Helper to check preconditions for property access. /// void EnsureState(State state) { if ( ((state & State.IsLocal) != (State)0) && isRemoteMachine) { throw new NotSupportedException(SR.GetString(SR.NotSupportedRemoteThread)); } if ((state & State.IsNt) != (State)0) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired)); } } } ////// Helper to open a thread handle. /// ///SafeThreadHandle OpenThreadHandle(int access) { EnsureState(State.IsLocal); return ProcessManager.OpenThread(threadInfo.threadId, access); } /// /// Resets the ideal processor so there is no ideal processor for this thread (e.g. /// any processor is ideal). /// public void ResetIdealProcessor() { // 32 means "any processor is fine" IdealProcessor = 32; } ////// Sets which processors the associated thread is allowed to be scheduled to run on. /// Each processor is represented as a bit: bit 0 is processor one, bit 1 is processor /// two, etc. For example, the value 1 means run on processor one, 2 means run on /// processor two, 3 means run on processor one or two. /// [Browsable(false)] public IntPtr ProcessorAffinity { set { SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_SET_INFORMATION | NativeMethods.THREAD_QUERY_INFORMATION); if (NativeMethods.SetThreadAffinityMask(threadHandle, new HandleRef(this, value)) == IntPtr.Zero) { throw new Win32Exception(); } } finally { CloseThreadHandle(threadHandle); } } } private ProcessThreadTimes GetThreadTimes() { ProcessThreadTimes threadTimes = new ProcessThreadTimes(); SafeThreadHandle threadHandle = null; try { threadHandle = OpenThreadHandle(NativeMethods.THREAD_QUERY_INFORMATION); if (!NativeMethods.GetThreadTimes(threadHandle, out threadTimes.create, out threadTimes.exit, out threadTimes.kernel, out threadTimes.user)) { throw new Win32Exception(); } } finally { CloseThreadHandle(threadHandle); } return threadTimes; } ////// Preconditions for accessing properties. /// ///enum State { IsLocal = 0x2, IsNt = 0x4 } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- SByteConverter.cs
- COM2ICategorizePropertiesHandler.cs
- HtmlElement.cs
- AttributeAction.cs
- SelectionChangedEventArgs.cs
- RegisteredHiddenField.cs
- Pen.cs
- NativeMethods.cs
- TrackingMemoryStreamFactory.cs
- ComponentEditorPage.cs
- XmlSchemaImporter.cs
- ListViewInsertionMark.cs
- CancellationTokenRegistration.cs
- ManualResetEvent.cs
- LocatorManager.cs
- ReadonlyMessageFilter.cs
- MetadataWorkspace.cs
- Persist.cs
- TextAction.cs
- ObjectStateEntryBaseUpdatableDataRecord.cs
- ProxyElement.cs
- Point4DValueSerializer.cs
- DirectionalLight.cs
- SmiXetterAccessMap.cs
- NamespaceList.cs
- WindowsSecurityTokenAuthenticator.cs
- ChangePassword.cs
- DiagnosticTrace.cs
- EmulateRecognizeCompletedEventArgs.cs
- ContractReference.cs
- SoapInteropTypes.cs
- StructuredTypeEmitter.cs
- WebPartPersonalization.cs
- HandlerBase.cs
- HostingEnvironmentException.cs
- XmlSchemaType.cs
- ToolBar.cs
- KeyInstance.cs
- FlowDocumentScrollViewerAutomationPeer.cs
- RowTypePropertyElement.cs
- DiagnosticsConfiguration.cs
- ConfigurationValues.cs
- EDesignUtil.cs
- DataColumn.cs
- WindowsFormsHelpers.cs
- PerformanceCounterCategory.cs
- TrackingQueryElement.cs
- CodeNamespaceCollection.cs
- ItemDragEvent.cs
- x509utils.cs
- SecurityVerifiedMessage.cs
- StreamingContext.cs
- SettingsProperty.cs
- NetStream.cs
- SmiMetaData.cs
- ComponentDispatcherThread.cs
- DataGridViewCellValidatingEventArgs.cs
- PreviewKeyDownEventArgs.cs
- StrongNameMembershipCondition.cs
- Helper.cs
- PageContent.cs
- ResourcesBuildProvider.cs
- XmlMapping.cs
- SamlNameIdentifierClaimResource.cs
- DBCSCodePageEncoding.cs
- ComboBoxRenderer.cs
- PinnedBufferMemoryStream.cs
- MobileListItemCollection.cs
- DataTableClearEvent.cs
- RootBuilder.cs
- EventArgs.cs
- ConnectionProviderAttribute.cs
- AuthenticationModuleElement.cs
- SqlCachedBuffer.cs
- ExpressionPrefixAttribute.cs
- SymLanguageVendor.cs
- PreviewPrintController.cs
- ConfigXmlComment.cs
- DataViewSettingCollection.cs
- HyperLink.cs
- FormsAuthenticationConfiguration.cs
- WebPartEditorApplyVerb.cs
- HScrollBar.cs
- BCLDebug.cs
- MethodExpr.cs
- FixedElement.cs
- WebServiceClientProxyGenerator.cs
- ArrayExtension.cs
- DataGridAutoGeneratingColumnEventArgs.cs
- CuspData.cs
- RegexReplacement.cs
- SecurityPermission.cs
- VisualTreeUtils.cs
- WorkflowViewService.cs
- ParallelQuery.cs
- SrgsToken.cs
- RuntimeHelpers.cs
- PhoneCallDesigner.cs
- InterleavedZipPartStream.cs
- SystemIPInterfaceProperties.cs