Net resources windows system

Windows System Resource Manager Overview

Applies To: Windows Server 2012

You can use Windows System Resource Manager to allocate processor and memory resources to applications, users, Remote Desktop Services sessions, and Internet Information Services (IIS) application pools.

With Windows System Resource Manager for the Windows ServerВ® 2012 operating system, you can manage server processor and memory usage with standard or custom resource policies. Managing your resources can help ensure that all the services provided by a single server are available on an equal basis or that your resources will always be available to high-priority applications, services, or users.

Windows System Resource Manager only manages processor resources when the combined processor load is greater than 70 percent. This means that it does not actively limit the resources that can be used by each consumer when processor load is low. When there is contention for processor resources, resource allocation policies help ensure minimum resource availability based on the management profile that you define.

Role/Feature description

You can use Windows System Resource Manager to:

Manage system resources (processor and memory) with preconfigured policies, or create custom policies that allocate resources per process, per user, per Remote Desktop Services session, or per Internet Information Services (IIS) application pool.

Use calendar rules to apply different policies at different times without manual intervention or reconfiguration.

Automatically select resource policies that are based on server properties and events (such as cluster events or conditions) or changes to installed physical memory or number of processors.

Collect resource usage data locally or in a custom SQL database. Resource usage data from multiple servers can be consolidated on a single computer running Windows System Resource Manager.

Create a computer group to help organize Remote Desktop Session Host servers that you want to manage. Policies can easily be exported or modified for an entire computer group.

Practical applications

Because Windows ServerВ 2008В R2 is designed to give as many resources as possible to non-operating system tasks, a server running a single role usually does not require resource management. However, when multiple applications and services are installed on a single server, they are not aware of competing processes. An unmanaged application or service will typically use all available resources to complete a task. Thus, it is important to use a tool such as Windows System Resource Manager to manage system resources on multipurpose servers. Using Windows System Resource Manager provides two key benefits:

More services can run on a single server because service availability can be improved through dynamically managed resources.

High-priority users or system administrators can access the system even during times of maximum resource load.

Methods of resource management

Windows System Resource Manager includes five built-in resource management policies that you can use to quickly implement management. In addition, you can create custom resource management policies to meet your specific needs.

Читайте также:  Антивирус касперского для линукса

Built-in resource management policies

You can enable built-in resource management policies by selecting the type of policy to use. No further configuration is required.

Equal per process

When the Equal_Per_Process resource allocation policy is managing the system, each running process is given equal treatment. For example, if a server that is running ten processes reaches 70 percent processor utilization, Windows System Resource Manager will limit each process to using 10 percent of the processor resources while they are in contention. Note that resources not used by low utilization processes will be allocated to other processes.

When the Equal_Per_User resource allocation policy is managing the system, processes are grouped according to the user account that is running them, and each of these process groups is given equal treatment. For example, if four users are running processes on the server, each user will be allocated 25 percent of the system resources to complete those processes. A user running a single application is allocated the same resources as a user running several applications. This policy is especially useful for application servers.

Equal per session

When the Equal_Per_Session resource allocation policy is managing the system, resources are allocated on an equal basis for each session connected to the system. This policy is for use with RD Session Host servers.

Equal per IIS application pool

When the Equal_Per_IISAppPool resource allocation policy is managing the system, each running IIS application pool is given equal treatment, and applications that are not in an IIS application pool can only use resources that are not being consumed by IIS application pools.

Weighted Remote Sessions

When the Weighted_Remote_Sessions resource allocation policy is managing the system, the processes are grouped according to the priority assigned with the user account. For example, if three users are remotely connected, the user assigned Premium priority will receive highest priority access to the CPU, the user assigned Standard priority will receive second priority to the CPU, and the user assigned Basic priority will receive lowest priority to the CPU. This policy is for use with RD Session Host servers.

When Weighted_Remote_Sessions is set as the managing policy, system management is delegated to the Windows Server 2012 scheduler, and Windows System Resource Manager only profiles the system. Setting or removing Weighted_Remote_Sessions as the managing policy requires a restart of the computer imposed by the kernel.

Custom resource management

You can use custom resource management methods to identify resource users and allocate resources to them based on your own criteria.

Process matching criteria

Enable you to select services or applications to be managed by resource allocation policy rules. You can choose by file name or command, or you can specify users or groups. For example, you could create a process matching criterion that applies management to the application iexplore.exe when it is run by the user Administrator.

Resource allocation policies

Allocate processor and memory resources to processes that are specified by the process matching criteria that you create.

Exclude applications, services, users, or groups from management by Windows System Resource Manager.

Note

You can also use command-line path matching in a resource allocation policy to exclude an application from management by only that policy.

Use a calendar interface to control one-time events or recurring changes to resource allocation. Different resource allocation policies can be active at different times of day, on different days of the week, or according to other scheduling paradigms.

Conditional policy application

Automatically switch resource allocation policies in response to certain system events (such as installing new memory or additional processors, starting or stopping a node, or changing the availability of a resource group in a cluster).

Removed or deprecated functionality

Windows System Resource Manager (WSRM) is deprecated beginning with Windows ServerВ® 2012. You should begin planning now to use alternate methods for any applications, code, or scenarios that depend on this feature. Windows System Resource ManagerВ is an administrative tool that controls how CPU and memory resources are allocated. For more information, see. Deprecated Features for Windows 7 and Windows Server 2008 R2

Application. Find Resource(Object) Метод

Определение

Выполняет поиск ресурса пользовательского интерфейса (например Style Brush , или) с указанным ключом и создает исключение, если запрошенный ресурс не найден (см. раздел ресурсы XAML). Searches for a user interface (UI) resource, such as a Style or Brush, with the specified key, and throws an exception if the requested resource is not found (see XAML Resources).

Параметры

Имя искомого ресурса. The name of the resource to find.

Возвращаемое значение

Запрошенный объект ресурса. The requested resource object. Если ресурс не найден, генерируется ResourceReferenceKeyNotFoundException. If the requested resource is not found, a ResourceReferenceKeyNotFoundException is thrown.

Исключения

Невозможно найти ресурс. The resource cannot be found.

Примеры

В следующем примере показано, как использовать FindResource для поиска ресурса, а также для решения, ResourceReferenceKeyNotFoundException Если ресурс не найден. The following example shows how to use FindResource to find a resource, and to handle ResourceReferenceKeyNotFoundException if the resource is not found.

Комментарии

FindResource сначала проанализируйте ресурсы области приложения для указанного ресурса. FindResource will first look in application-scope resources for the specified resource. Ресурсы области приложения управляются с помощью Application и предоставляются из Resources Свойства. Application-scope resources are managed by Application, and are exposed from the Resources property. Если указанный ресурс не найден в наборе ресурсов области приложения, FindResource Далее выполняется поиск по системным ресурсам. If the specified resource is not found in the set of application-scope resources, FindResource then next searches the system resources. Системные ресурсы — это ресурсы оболочки, определенные пользователем, включая цвета, шрифты и конфигурации оболочки. System resources are shell resources defined by the user, and include colors, fonts, and shell configurations. Они предоставляются из SystemColors SystemFonts типов, и соответственно в SystemParameters качестве статических свойств. These are exposed from the SystemColors, SystemFonts, and SystemParameters types, respectively, as static properties. Чтобы использовать FindResource для их получения, эти типы также предоставляют свойства ключа ресурса, предназначенные для передачи, FindResource например IconWidthKey . To use FindResource to acquire them, these types also expose resource key properties that are designed to be passed to FindResource; for example, IconWidthKey.

Поскольку FindResource возвращает объект, необходимо привести возвращаемое значение к соответствующему типу, если ресурс найден. Because FindResource returns an object, you must cast the returned value to the appropriate type if the resource is found.

При вызове этого метода для ключа, который не удается найти, создается исключение. If you call this method for a key that cannot be found, an exception is thrown. Если вы не хотите обрабатывать исключения, являющиеся результатом вызова метода FindResource , вызовите TryFindResource вместо него TryFindResource ссылку, null если не удается найти запрошенный ресурс и не вызывается исключение. If you do not want to handle exceptions that result from calling FindResource, call TryFindResource instead; TryFindResource returns a null reference when a requested resource cannot be found, and does not throw an exception.

Этот метод является потокобезопасным и может быть вызван из любого потока. This method is thread safe and can be called from any thread.

.NET Core Workers как службы Windows

В .NET Core 3.0 мы представляем новый тип шаблона приложения под названием Worker Service. Этот шаблон предназначен для того, чтобы дать вам отправную точку для написания долго-работающих сервисов в .NET Core. В этом пошаговом руководстве мы создадим worker и запустим его в качестве службы Windows.

Создание worker

Примечание. В наших предварительных версиях шаблон worker находится в том же меню, что и веб-шаблоны. Это изменится в будущем выпуске. Мы намерены разместить шаблон Worker Service непосредственно в мастере создания нового проекта.

Создание Worker в Visual Studio

Создание Worker в командной строке

Выполните dotnet new worker

Запуск в виде службы Windows

Чтобы запустить в качестве службы Windows, нам нужно, чтобы наш worker видел сигналы запуска и остановки от типа ServiceBase .NET, который связывает системы Windows Service с приложениями .NET. Для этого нужно:

Добавить пакет NuGet Microsoft.Extensions.Hosting.WindowsServices

Добавить вызов UseServiceBaseLifetime к HostBuilder в Program.cs

Этот метод делает несколько вещей. Во-первых, он проверяет, действительно ли приложение работает в качестве службы Windows, если это не так, то он выполняет noops, что делает этот метод безопасным для вызова при локальном запуске или в качестве службы Windows.

Во-вторых, он настраивает ваш хост на использование ServiceBaseLifetime . ServiceBaseLifetime работает с ServiceBase чтобы помочь контролировать время жизни вашего приложения при запуске в качестве службы Windows. Это переопределяет стандартный ConsoleLifetime который обрабатывает такие сигналы, как CTL + C.

Установка Worker

Как только мы получили worker использовав ServiceBaseLifetime нам нужно установить его:

Во-первых, давайте опубликуем приложение. Мы установим Службу Windows in-place, что означает, что исполняемый файл будет заблокирован при каждом запуске службы. Публикация — это хороший способ убедиться, что все файлы, необходимые для запуска службы, находятся в одном месте и готовы к установке.

Далее можно использовать sc utility в командной строке администратора

Примечание о безопасности: Эта команда запускает службу как локальную систему, которая не является тем, что нужно. Вместо этого вы должны создать service account и запустить службу Windows в качестве этой учетной записи. Мы не будем говорить об этом здесь, но здесь есть некоторая документация по ASP.NET: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.2

Логирование

У системы логирования есть сервис «Event Log», который может отправлять сообщения логов непосредственно в журнал событий Windows. Чтобы войти в журнал событий, вы можете добавить Microsoft.Extensions.Logging.EventLog пакет, а затем изменить ваш Program.cs :

Дальнейшая работа

В следующих предварительных версиях мы планируем улучшить использование Workers с Windows Services:

  1. Переименуем UseWindowsServiceBaseLifetime на UseWindowsService
  2. Добавим автоматическую и улучшенную интеграцию с журналом событий при запуске в качестве службы Windows.

Читайте также:  Windows 10 лагает браузер
Оцените статью
Note