Background process in windows

Run in the background indefinitely

To provide the best experience for users, Windows imposes resource limits on Universal Windows Platform (UWP) apps. Foreground apps are given the most memory and execution time; background apps get less. Users are thus protected from poor foreground app performance and heavy battery drain.

However, developers writing UWP apps for personal use (that is, side loaded apps that won’t be published in the Microsoft Store), or developers writing Enterprise UWP apps, may want to use all resources available on the device without any background or extended execution throttling. Line of business and personal UWP applications can use APIs in the Windows Creators Update (version 1703) to turn off throttling. Be aware that you can’t put an app into the Microsoft Store if it uses these APIs.

Run while minimized

UWP apps move to a suspended state when they are not running in the foreground. On desktop, this occurs when a user minimizes the app. Apps use an extended execution session in order to continue running while minimized. The extended execution APIs that are accepted by the Microsoft Store are detailed in Postpone app suspension with extended execution.

If you are developing an app that is not intended to be submitted into the Microsoft Store, then you can use the ExtendedExecutionForegroundSession with the extendedExecutionUnconstrained restricted capability so that your app can continue to run while minimized, regardless of the energy state of the device. В

The extendedExecutionUnconstrained capability is added as a restricted capability in your app’s manifest. See App capability declarations for more information about restricted capabilities.

Add the xmlns:rescap XML namespace declaration, and use the rescap prefix to declare the capability.

For more information, see the Restricted Capabilities section of App capability declarations.

When you use the extendedExecutionUnconstrained capability, ExtendedExecutionForegroundSession and ExtendedExecutionForegroundReason are used rather than ExtendedExecutionSession and ExtendedExecutionReason. The same pattern for creating the session, setting members, and requesting the extension asynchronously still applies: 

You can request this extended execution session as soon as the app comes to the foreground. Unconstrained extended execution sessions are not limited by energy quotas or by the operating system battery saver. As long as a reference to the session object exists, the app will stay in the running state and not enter the suspended state. If the app is closed by the user, the session will be revoked.

Registering for the Revoked event will enable your app to do any cleanup work required. In the suspending state, you can create an extended execution session with ExtendedExecutionReason.SavingData to save user data before the app is terminated and removed from memory.

Run background tasks indefinitely

In the Universal Windows Platform, background tasks are processes that run in the background without any form of user interface. Background tasks may generally run for a maximum of twenty-five seconds before they are cancelled. Some of the longer-running tasks also have a check to ensure that the background task is not sitting idle or using memory. In the Windows Creators Update (version 1703), the extendedBackgroundTaskTime restricted capability was introduced to remove these limits. The extendedBackgroundTaskTime capability is added as a restricted capability in your app’s manifest file:

Add the xmlns:rescap XML namespace declaration, and use the rescap prefix to declare the capability.

For more information, see the Restricted Capabilities section of App capability declarations.

This capability removes execution time limitations and the idle task watchdog. Once a background task has started, whether by a trigger or an app service call, once it takes a deferral on the BackgroundTaskInstance provided by the Run method, it can run indefinitely. If the app is set to Managed By Windows, then it still may have an energy quota applied to it, and its background tasks will not activated when Battery Saver is active. This can be changed with OS settings. More information is available in Optimizing Background Activity.

Читайте также:  Ограничена скорость скачивания windows 10

The Universal Windows Platform monitors background task execution to ensure good battery life and a smooth foreground app experience. However, personal apps and Enterprise line-of-Business apps can use extended execution and the extendedBackgroundTaskTime capability to create apps that will run as long as needed regardless of the device’s resource availability.

Be aware that the extendedExecutionUnconstrained and extendedBackgroundTaskTime capabilities can override default policy for UWP apps and may cause significant battery drain. Before using these capabilities, first confirm that the default extended execution and background task time policies do not meet your needs and perform testing in battery-constrained conditions to understand the impact your app will have on a device.

Desktop app runs as background process?

After upgrading to Windows 10 from Windows 7 I’m having problems with a desktop app (a dictionary) which won’t run as a normal app, but instead runs as a background process. It just won’t show up and when I check the Task Manager I see it listed among Processes instead of Apps. Any idea on how do I fix this? I tried to run it in compatibility mode for all possible previous windows versions, but it doesn’t work. Sometimes, if I run the program several times and leave the respective backrgound instances running, the app appears, but I don’t know why, neither can I reproduce the behavior. Any help would be appreciated.

Replies (5) 

Thank you for posting in Microsoft Community. I understand your concern and I am glad to assist you.

You may try this suggestion.

  1. Open Settings or Press Windows + I keys
  2. Go to privacy
  3. Click on Background apps.
  4. locate the desktop app and slide it to off.
  5. You can do this for individual apps.

You may boot your system in safe mode and check if the issue persist.

If the issue do not occur in safe mode. You may scan your system for viruses and remove them as most likely it would be a virus that made this change in behavior of Windows.

Hope this post helps. Get back to us for further queries. We are happy to help!

5 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

Thank you for your reply, Joy.

I tried what you suggested and unfortunately my application isn’t listed there. It’s not a Windows 10 app, but an older 32-bit application that should run in windowed mode, but for some reason when I double click its icon it starts as a background process instead of a windowed app. That happens in most of the cases, fortunately, at the end it somehow starts as a desktop app. But I cannot reproduce this behavior.

As a temporary solution, to keep it in windowed mode I never shut the computer down, but instead I leave the application running and put the computer to sleep.

Is there a setting to instruct Windows to run my application as a desktop application and not as a background process? Thank you.

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

Создание и регистрация фоновой задачи, выполняемой внутри процесса Create and register an in-process background task

Важные API Important APIs

В этом разделе рассказывается, как создать и зарегистрировать фоновую задачу, которая будет выполняться в том же процессе, что и ваше приложение. This topic demonstrates how to create and register a background task that runs in the same process as your app.

Выполняемые внутри процесса фоновые задачи проще реализовать, чем фоновые задачи, выполняемые вне процесса. In-process background tasks are simpler to implement than out-of-process background tasks. Однако они менее устойчивы. However, they are less resilient. Сбой выполнения кода в фоновой задаче внутри процесса затронет работу вашего приложения. If the code running in an in-process background task crashes, it will take down your app. Также обратите внимание, что триггеры DeviceUseTrigger, DeviceServicingTrigger и IoTStartupTask нельзя использовать в рамках модели внутри процесса. Also note that DeviceUseTrigger, DeviceServicingTrigger and IoTStartupTask cannot be used with the in-process model. Запуск фоновой задачи VoIP в приложении также невозможен. Activating a VoIP background task within your application is also not possible. Использование этих триггеров и задач все еще поддерживается в рамках модели фоновой задачи, выполняемой вне процесса. These triggers and tasks are still supported using the out-of-process background task model.

Читайте также:  Linux mint очень тихий звук

Имейте в виду, что фоновые задачи можно остановить (даже внутри фонового процесса приложения), если время их выполнения выходит за заданные пределы. Be aware that background activity can be terminated even when running inside the app’s foreground process if it runs past execution time limits. Для некоторых целей обеспечение устойчивости при выделении работы в фоновую задачу, выполняющуюся в отдельном процессе, по-прежнему является целесообразным. For some purposes the resiliency of separating work into a background task that runs in a separate process is still useful. Выделение фоновой работы в задачу, не связанную с приложением переднего плана, может быть лучшим решением, когда для работы не требуется обмен данными с приложением переднего плана. Keeping background work as a task separate from the foreground application may be the best option for work that does not require communication with the foreground application.

Основы Fundamentals

Модель с выполнением внутри процесса оптимизирует жизненный цикл приложения с помощью улучшенных уведомлений, когда приложение работает на переднем плане или в фоновом режиме. The in-process model enhances the application lifecycle with improved notifications for when your app is in the foreground or in the background. Для этих переходов между режимами работы приложения доступно два новых события из объекта Application: EnteredBackground и LeavingBackground. Two new events are available from the Application object for these transitions: EnteredBackground and LeavingBackground. Эти события встраиваются в жизненный цикл приложения на основании состояния видимости вашего приложения. Дополнительные сведения об этих событиях и об их влиянии на жизненный цикл приложения см. в разделе Жизненный цикл приложения. These events fit into the application lifecycle based on the visibility state of your application Read more about these events and how they affect the application lifecycle at App lifecycle.

На высоком уровне вы будете управлять событием EnteredBackground для запуска вашего кода, который будет выполняться одновременно с выполнением вашего приложения в фоновом режиме, и событием LeavingBackground, чтобы знать, когда приложение перемещается на передний план. At a high level, you will handle the EnteredBackground event to run your code that will execute while your app is running in the background, and handle LeavingBackground to know when your app has moved to the foreground.

Регистрация триггера фоновой задачи Register your background task trigger

Регистрация фонового действия внутри процесса выполняется практически так же, как и регистрация фонового действия вне процесса. In-process background activity is registered much the same as out-of-process background activity. Регистрация всех фоновых триггеров выполняется с помощью класса BackgroundTaskBuilder. All background triggers start with registration using the BackgroundTaskBuilder. Построитель упрощает процесс регистрации фоновой задачи путем установки всех необходимых значений в одном месте. The builder makes it easy to register a background task by setting all required values in one place:

Универсальные приложения для Windows должны вызвать RequestAccessAsync перед регистрацией любых типов фоновых триггеров. Universal Windows apps must call RequestAccessAsync before registering any of the background trigger types. Чтобы универсальное приложение для Windows продолжало правильно работать после выпуска обновления, необходимо вызвать метод RemoveAccess, а затем — метод RequestAccessAsync при запуске приложения после обновления. To ensure that your Universal Windows app continues to run properly after you release an update, you must call RemoveAccess and then call RequestAccessAsync when your app launches after being updated. Дополнительные сведения см. в разделе Руководство по фоновым задачам. For more information, see Guidelines for background tasks.

Для фоновых действий внутри процесса установка значения свойства TaskEntryPoint. не выполняется. За счет того, что значение для него не задается, появляется возможность использовать точку входа по умолчанию — новый защищенный метод в объекте Application под названием OnBackgroundActivated(). For in-process background activities you do not set TaskEntryPoint. Leaving it blank enables the default entry point, a new protected method on the Application object called OnBackgroundActivated().

После регистрации триггера он будет запущен с учетом типа триггера, указанного в методе SetTrigger. Once a trigger is registered, it will fire based on the type of trigger set in the SetTrigger method. В примере кода, приведенном выше, используется триггер TimeTrigger, который будет срабатывать через 15 минут после его регистрации. In the example above a TimeTrigger is used, which will fire fifteen minutes from the time it was registered.

Читайте также:  Восстановление старой версии windows

Добавление условия, которое будет контролировать время запуска задачи (необязательно) Add a condition to control when your task will run (optional)

Вы можете добавить условие, чтобы контролировать, в какой момент времени после возникновения события триггера запустится ваша задача. You can add a condition to control when your task will run after the trigger event occurs. Например, если вы не хотите, чтобы задача запускалась в отсутствие пользователя, используйте условие UserPresent. For example, if you don’t want the task to run until the user is present, use the condition UserPresent. Список возможных условий см. в статье SystemConditionType. For a list of possible conditions, see SystemConditionType.

Следующий пример кода назначает условие, при котором необходимо присутствие пользователя: The following sample code assigns a condition requiring the user to be present:

Размещение кода фонового действия в методе OnBackgroundActivated() Place your background activity code in OnBackgroundActivated()

Добавьте код фоновых действий в онбаккграундактиватед , чтобы ответить на фоновый триггер при срабатывании. Put your background activity code in OnBackgroundActivated to respond to your background trigger when it fires. OnBackgroundActivated может обрабатываться как IBackgroundTask.Run. OnBackgroundActivated can be treated just like IBackgroundTask.Run. Метод имеет параметр баккграундактиватедевентаргс , который содержит все, что доставляет метод Run . The method has a BackgroundActivatedEventArgs parameter, which contains everything that the Run method delivers. Например, в App.xaml.cs: For example, in App.xaml.cs:

Обработка хода выполнения и завершения фоновых задач Handle background task progress and completion

Ход выполнения и завершения задачи можно отслеживать так же, как и аналогичные состояния фоновых задач с несколькими процессами (см. раздел Отслеживание хода выполнения и завершения фоновых задач), однако, скорее всего, вы обнаружите, что эти состояния выполнения и завершения проще отслеживать, используя соответствующие переменные из вашего приложения. Task progress and completion can be monitored the same way as for multi-process background tasks (see Monitor background task progress and completion) but you will likely find that you can more easily track them by using variables to track progress or completion status in your app. Это преимущество обеспечивается за счет выполнения кода фонового действия в рамках того же процесса, в котором работает приложение. This is one of the advantages of having your background activity code running in the same process as your app.

Обработка отмены фоновых задач Handle background task cancellation

Отмена фоновых задач внутри процесса выполняется так же, как и отмена фоновых задач, выполняемых вне процесса (см. раздел Обработка отмененной фоновой задачи). In-process background tasks are cancelled the same way as out-of-process background tasks are (see Handle a cancelled background task). Имейте в виду, что обработчик события BackgroundActivated должен выйти из процесса, перед тем как произойдет отмена. В противном случае будет завершен весь процесс. Be aware that your BackgroundActivated event handler must exit before the cancellation occurs, or the whole process will be terminated. В случае непредвиденного закрытия фонового приложения при отмене фоновой задачи убедитесь, что обработчик вышел из процесса до отмены задачи. If your foreground app closes unexpectedly when you cancel the background task, verify that your handler exited before the cancellation occured.

Манифест The manifest

В отличие от фоновых задач, выполняемых вне процесса, добавлять сведения о фоновой задаче в манифест пакета, чтобы обеспечить выполнение фоновых задач внутри процесса, не требуется. Unlike out-of-process background tasks, you are not required to add background task information to the package manifest in order to run in-process background tasks.

Сводка и дальнейшие действия Summary and next steps

Теперь вы знакомы с основами написания фоновой задачи, выполняемой внутри процесса. You should now understand the basics of how to write a in-process background task.

В статьях ниже можно найти справочник по API, концептуальное руководство по фоновым задачам и подробные инструкции по созданию приложений, использующих фоновые задачи. See the following related topics for API reference, background task conceptual guidance, and more detailed instructions for writing apps that use background tasks.

Учебные статьи с подробными сведениями о фоновых задачах Detailed background task instructional topics

Руководство по фоновым задачам Background task guidance

Справочник по API для фоновых задач Background Task API Reference

Оцените статью