How to connect background tasks to Avalonia. Conditionally, I need messages to be uploaded to a file every 5 minutes in my desktop application for windows and linux. I didn't find a question on this topic on GitHub and it talked about the AsyncAwaitBestPractices. However, it only implements the SaveFireAndForget method. Which is not suitable in this case.
I tried to do it with Quartz.NET, but it doesn't works.
public static class DependencyInjection
{
public static void AddCommonServices(this IServiceCollection services)
{
services.AddSingleton<IFileService, FileService>();
services.AddTransient<MainWindowViewModel>();
services.AddQuartz(option =>
{
var jobKey = JobKey.Create(nameof(LoggingBackgroundJob));
option
.AddJob<LoggingBackgroundJob>(jobKey)
.AddTrigger(trigger =>
trigger
.ForJob(jobKey)
.WithSimpleSchedule(schedule =>
schedule.WithIntervalInSeconds(5).RepeatForever()
)
);
});
services.AddQuartzHostedService(option =>
{
option.WaitForJobsToComplete = true;
});
}
}
namespace AvaloniaApplication1
{
public partial class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
// Line below is needed to remove Avalonia data validation.
// Without this line you will get duplicate validations from both Avalonia and CT
BindingPlugins.DataValidators.RemoveAt(0);
var collection = new ServiceCollection();
collection.AddCommonServices();
var services = collection.BuildServiceProvider();
var vm = services.GetRequiredService<MainWindowViewModel>();
desktop.MainWindow = new MainWindow
{
DataContext = vm
};
}
base.OnFrameworkInitializationCompleted();
}
}
}