I read a few guides how to create and register a background task. There is a file that is contained in a separate project. File Contents:

namespace background { public sealed class MyBackgroundTask : IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral _deferral = taskInstance.GetDeferral(); await DoWork(taskInstance); throw new NotImplementedException(); _deferral.Complete(); } private async Task DoWork(IBackgroundTaskInstance taskInstance) { //задача, которая должна выполнятся в фоновом... } } } 

And part of the code that is written to a specific file in the main project:

 var taskRegistered = false; var exampleTaskName = "MyBackgroundTask"; foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == exampleTaskName) { taskRegistered = true; break; } } var builder = new BackgroundTaskBuilder(); builder.Name = exampleTaskName; builder.TaskEntryPoint = "backgroung.MyBackgroundTask"; appTrigger = new ApplicationTrigger(); builder.SetTrigger(appTrigger); appTrigger.RequestAsync(); 

As far as I understood, appTrigger.RequestAsync(); should run a background task in the place where it is written. But, just on this line, it begins to swear in this way and does not allow the program to continue working after this line:

Warning CS4014 This is the case. Consider applying the operator.

Can you please tell how you can fix the problem?

  • "But, just for this line, it starts to swear in this way and does not allow the program to work further " - I do not believe it! - Pavel Mayorov
  • On the question - what is IBackgroundTaskInstance ? What is BackgroundTaskDeferral ? What is ApplicationTrigger ? Why is everything so hard to do? What is the general problem solved? What do you understand by the words "background task"? - Pavel Mayorov 2:21 pm
  • one
    Seriously, this is the best way to write a background task from all that I have seen. No just to Thread or Task the same use in a couple of lines. - DEADMC

1 answer 1

Remove async from the Run method; it should not be asynchronous at all. That is, you need to replace:

 public async void Run(IBackgroundTaskInstance taskInstance) 

on

 public void Run(IBackgroundTaskInstance taskInstance) 

In general, the code was correct, another thing is that the guide from which you took BackgroundTask is designed for use by triggers, and isn’t necessary when running async directly. But in general, it is still preferable to use Task or Thread for such tasks, since The main use of BackgroundTask is background trigger work, i.e. in the case of a limited range of specific actions. In 90% of cases, this is generally not necessary, given that, based on the documentation on SystemTriggerType , the cat wept there for possible actions.