How to use Page Background Tasks in Business Central – Beginner

Page Background Tasks is a feature introduced in Microsoft Dynamics 365 Business Central (formerly Dynamics NAV) that allows developers to offload time-consuming tasks to run asynchronously in the background. This helps improve the responsiveness of the user interface and overall system performance by executing resource-intensive operations without blocking the user’s interaction with the application. Here’s how Page Background Tasks work:

  • Asynchronous Execution: When a user initiates a long-running operation, such as data processing, report generation, or data synchronization, the system can initiate a background task to perform the operation asynchronously.
  • Non-Blocking User Interface: While the background task is running, the user can continue working with the application without experiencing delays or interruptions caused by the long-running operation. This ensures that the user interface remains responsive and interactive.
  • Progress Feedback: The user may be provided with feedback on the progress of the background task, such as a progress bar or status indicator, to keep them informed about the task’s status.
  • Completion Notification: Once the background task completes, the user may receive a notification indicating that the operation has finished. This allows the user to review the results or continue working with the application as needed.
  • Error Handling: If an error occurs during the execution of the background task, appropriate error handling mechanisms should be implemented to handle the error gracefully and provide feedback to the user, if necessary.
  • Task Queuing: The system may queue background tasks to ensure that they are executed in a controlled manner, especially in scenarios where multiple tasks are initiated concurrently.
  • Resource Management: Developers should consider resource management aspects, such as managing memory usage and database connections, to ensure that background tasks do not negatively impact system performance or scalability.

Overall, Page Background Tasks provide a mechanism for executing long-running operations asynchronously, improving the responsiveness of the user interface and enhancing the overall performance and user experience of Microsoft Dynamics 365 Business Central.

Practical example of when Page Background Tasks should be used but also when it should not

When to Use Page Background Tasks:

  • Scenario: Generating Complex Reports
    • Requirement: Users need to generate complex reports that involve aggregating large amounts of data and performing intensive calculations.
    • Usage: Instead of generating the report synchronously, which could potentially block the user interface and cause delays, a background task can be initiated to generate the report asynchronously. This allows users to continue working with the application while the report is being generated in the background.
  • Scenario: Data Synchronization
    • Requirement: Data from external systems needs to be synchronized with Microsoft Dynamics 365 Business Central periodically.
    • Usage: Rather than executing the data synchronization process synchronously, which could take a significant amount of time and potentially impact system performance, a background task can be triggered to perform the data synchronization asynchronously. This ensures that users can continue using the application while the synchronization process is running in the background.

When Not to Use Page Background Tasks:

  • Scenario: Real-time Data Processing
    • Requirement: Users expect immediate feedback or results for their actions, such as processing a transaction or updating records.
    • Usage: In scenarios where real-time processing is required, such as processing a sales order or updating inventory levels, using a background task may not be appropriate. Executing these operations synchronously ensures that users receive immediate feedback and maintains the integrity and consistency of the data.
  • Scenario: Lightweight Operations
    • Requirement: Users perform lightweight operations that do not require significant processing time or resources.
    • Usage: For simple or quick operations, such as retrieving a small set of records or performing basic calculations, initiating a background task may introduce unnecessary complexity and overhead. In such cases, executing the operation synchronously directly within the user interface may be more straightforward and efficient.

Summary

In summary, Page Background Tasks are beneficial for offloading time-consuming operations that could potentially block the user interface or impact system performance. However, they should be used judiciously and only for operations where asynchronous execution provides tangible benefits without compromising the user experience or data integrity. For lightweight or real-time operations, executing tasks synchronously may be more appropriate.

Example of a simple implementation of Page Background Tasks

Below is a practical example in AL code that demonstrates how to implement a simple Page Background Task in Microsoft Dynamics 365 Business Central. In this example, we will create a page that allows a user to trigger a background task to update the customer records’ credit limits.

Step 1: Create a Codeunit for the Background Task

First, create a codeunit that performs the background task of updating the credit limits for customer records.

codeunit 50001 "Update Customer Credit Limit"
{
    Subtype = Normal;

    trigger OnRun()
    begin
        UpdateCreditLimits();
    end;

    local procedure UpdateCreditLimits()
    var
        CustomerRec: Record Customer;
    begin
        if CustomerRec.FindSet() then begin
            repeat
                CustomerRec."Credit Limit (LCY)" := CustomerRec."Credit Limit (LCY)" + 1000;
                CustomerRec.Modify();
            until CustomerRec.Next() = 0;
        end;
    end;
}

Step 2: Create a Page to Trigger the Background Task

Next, create a page that allows the user to trigger the background task.

page 50001 "Customer Credit Limit Update"
{
    PageType = Card;
    ApplicationArea = All;
    Caption = 'Customer Credit Limit Update';

    layout
    {
        area(content)
        {
            group(Group)
            {
                field(Status; StatusTxt)
                {
                    ApplicationArea = All;
                }
                action(TriggerUpdate)
                {
                    ApplicationArea = All;
                    Caption = 'Update Credit Limits';
                    trigger OnAction()
                    var
                        BackgroundTask: Record "Background Task";
                        RecRef: RecordRef;
                        BackgroundTaskId: Guid;
                    begin
                        BackgroundTask.Initialize(RecRef, Codeunit::"Update Customer Credit Limit", BackgroundTaskId);
                        BackgroundTask.Insert();
                        StatusTxt := 'Background task started...';
                    end;
                }
            }
        }
    }

    var
        StatusTxt: Text[100];
}

Step 3: Register the Background Task in the System App

To ensure the background task codeunit can be used, register it in the System App.

  1. Open the Background Task table (ID 2000000201).
  2. Register your codeunit in this table.
tableextension 50001 BackgroundTaskExtension extends "Background Task"
{
    trigger OnAfterInsert()
    begin
        if "Object Type" = ObjectType::Codeunit then
            case "Object ID" of
                Codeunit::"Update Customer Credit Limit":
                    StartBackgroundTask();
            end;
    end;

    local procedure StartBackgroundTask()
    var
        BackgroundTaskRec: Record "Background Task";
    begin
        if BackgroundTaskRec.Get("Task ID") then
            Codeunit.Run(BackgroundTaskRec."Object ID", BackgroundTaskRec);
    end;
}

Summary

In this example, we’ve implemented a simple Page Background Task in AL code that performs the following:

  1. Codeunit: Defines the task to update customer credit limits.
  2. Page: Provides a UI for users to trigger the background task.
  3. Table Extension: Ensures the background task is registered and executed.

This setup allows the user to trigger a long-running operation (updating customer credit limits) without blocking the user interface, enhancing the application’s responsiveness.

Share the Post:

Related Posts