Creating a background task handler: Best practices
Best practices when creating a new background task handler lets you get the best out of your customization.
Add the specific error number
Throw the BackgroundTaskException with the specific error number to inform the background task service when the handler cannot finish execution successfully. An exception thrown by a handler informs the background task service that the handler could not fulfil its task. If configured accordingly, the service will use the error number to re-try the execution. When the task cannot be re-tried any more, the service will move it to the Failed status. Any exception that does not have an error number thrown by the handler will be treated as if it had the error number -1.
Check if you can end the event
When a handler cannot finish successfully, use the IBackgroundTaskHandlerContext.WillRetryOnError method to know if you can end the event. Normally, you should end the event whether the handler finished successfully or not. However, you should remember that when the handler failed to execute, the background task service can re-try it. In this case you should postpone ending the event until you know the service will not re-try the execution anymore.
Initialize method
Avoid throwing exceptions in the Initialize method. The initialize method is called before the run. At that moment the context is not yet available, which means you cannot close the event and you cannot use the IBackgroundTaskHandlerContext.WillRetryOnError method either. For background tasks, perform most of your initializations directly inside the Run method.
Byte order mark
When passing the stream, encode it with Unicode (UTF-16) with the byte order mark. The byte order mark indicates the encoding of the stream. Without it, you might not be able to decode it properly.
Avoid opening transactions explicitly
Accessing the application using standard endpoints will open the transaction for you.