简体   繁体   中英

Await and fire-and-forget in .NET Core

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;
        }

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 (eg, Azure Queue / Amazon SQS / etc.), and 2) have a background service (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM