It turns out that it is indeed possible to create a WinUI 3 desktop app that supports Background Tasks in the way that this is possible with a pure UWP or a UWP desktop bridge app.
Unfortunately Visual Studio 2019 prev.2 doesn't support this immediately with any of the available project templates. Luckily enough BrunoBlanes (see Question: Is it possible to create an out-of-process background task in a Desktop application as is with UWP?) explained me how to do this.
Because not everything is obvious I will describe the various steps to take.
This is what you have to do:
- Create a Windows Runtime Component (WRC) project to implement the background task. Do this in Visual Studio 2019 by choosing the c# Windows Runtime Component (WinUI in UWP) project template and selecting 10.0.19041.0 as target version. Add your background task class (inheriting from
IBackgroundTask
). - Create a UWP hosting app for the above WRC. Choose the c# Blank App(WinUI in UWP) project template and select 10.0.19041.0 as target version.
- Do the following in the UWP hosting app project:
- Rename
App.xaml
andApp.xaml.c
s toMain.xaml
andMain.xaml.cs
en rename theApp
class toMain
(in bothMain.xaml
andMain.xaml.cs
). - Delete
MainPage.xaml
andMainPage.xaml.cs
. - In
Main.xaml.cs
: Changeusing Microsoft.UI.Xaml
tousing Windows.UI.Xaml
, keep only an emptyMain
class constructor, and delete all other usings. - Delete the
<Application.Resources>
entry completely inMain.xaml
. - Add a reference to the above WRC project.
- Rename
- Close the solution and remove the
Microsoft.WinUI
reference by deleting the WinUIPackageReference
in both the WRC and the hosting project file. - Open the solution. You then might still have to remove the
Microsoft.ApplicationModel.Resources.winmd
reference and all theVCLib
references in both projects before the WinUI reference actually disappears.
You are now good to go.
- Add the hosting app to your desktop packaging project
- Add the necessary extensions in the
Package.appxmanifest
file of the packaging project - Do the necessary background task registrations in the code of the Desktop App project.
Yes that works when it is a WPF app with WPF user controls but it will not work when one also wants to make use of the modern UI controls, like Xaml Islands.
See Can't make release build with a WPF desktop app that is using Xaml Islands and Background Tasks
My question is specifically about WPF using WinUI 3 and .Net 5. I just want to understand whether Background Tasks using that architecture should work now, will work in the future, or will never work.