示例#1
0
        public static IDisposable SetThreadAffinity(int threadCount = 1, bool assignEvenly = false)
        {
            Contract.Assert(threadCount > 0, nameof(threadCount) + " must be greater than zero!");
            Contract.EndContractBlock();

            var original = new RefValue <IntPtr>();

            return
                (new ManagedDelegateDisposable(
                     () =>
            {
                var mask = CalculateAffinityMask(threadCount, assignEvenly);

                // disabling .NET thread management
                Thread.BeginThreadAffinity();
                // setting correctly affinity
                original.Value = SetThreadAffinityMask(GetCurrentThread(), new IntPtr(mask));

                if (original.Value == IntPtr.Zero)
                {
                    original.Value = Process.GetCurrentProcess().ProcessorAffinity;
                }
            },
                     () =>
            {
                // reverting to process affinity
                SetThreadAffinityMask(GetCurrentThread(), original.Value);
                // enabling .NET thread management
                Thread.EndThreadAffinity();
            }));
        }
示例#2
0
        public static IDisposable SetProcessAffinity(int threadCount = 1, bool assignEvenly = false)
        {
            Contract.Assert(threadCount > 0, nameof(threadCount) + " must be greater than zero!");
            Contract.EndContractBlock();

            var original = new RefValue <IntPtr>();

            return
                (new ManagedDelegateDisposable(
                     () =>
            {
                var mask = CalculateAffinityMask(threadCount, assignEvenly);

                // disable .NET thread management
                Thread.BeginThreadAffinity();

                // set process affinity
                using (var process = Process.GetCurrentProcess())
                {
                    original.Value = process.ProcessorAffinity;
                    process.ProcessorAffinity = new IntPtr(mask);
                }
            },
                     () =>
            {
                // revert process affinity
                using (var process = Process.GetCurrentProcess())
                {
                    original.Value = process.ProcessorAffinity;
                    process.ProcessorAffinity = original;
                }

                // enable .NET thread management
                Thread.EndThreadAffinity();
            }));
        }