Await and fire-and-forget in .NET Core

1.5k Views Asked by At

I'm working on a Blazor application.
When a user fills in a form the data needs to be saved to a table and a longer task needs to be run.
The user doesn't need to wait for this longer task to be completed. He will be notified later.
But when the long task is finished the table entry needs to be updated.
How to do this?

This is my current code which blocks to user until all is finished:

        public async Task<Client> Create(Client client)
        {
            client.DatabaseCreated = false;

            await _context.Clients.AddAsync(client);
            await _context.SaveChangesAsync();
            Debug.WriteLine("Client added");

            // Run longer task.
            try
            {
                // TODO: Don't wait for it:
                var longTask= myLongTask(client.Code, client.Id);
                // update table entry
                client.DatabaseCreated = true;
                var updateClient = _context.SaveChangesAsync();
                await Task.WhenAll(longTask, updateClient);
                Debug.WriteLine("Client updated");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            Debug.WriteLine("Client returned");
            return client;
        }
1

There are 1 best solutions below

4
On

The user doesn't need to wait for this longer task to be completed. He will be notified later. How to do this?

To do this in a reliable way, you would need to 1) have a reliable queue (e.g., Azure Queue / Amazon SQS / etc.), and 2) have a background service (e.g., ASP.NET Core Background Service / Azure Function / Amazon Lambda / etc.). The ASP.NET API would just place a message onto the queue and then return; the background service reads from the queue and processes the messages.