Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire & Forget calls in Azure Functions

I have a long running task in an Azure function which I want to run in a background thread using Task.Run. I don't care about the result.

public static async Task Run(...)
{
 var taskA = await DoTaskA();     
 Task.Run(new Action(MethodB));
 ....
 // return result based on taskA
}

Is this an acceptable pattern in Azure functions? (this is an HTTP trigger function)

I know this could also be done by adding a message to a queue and have another function execute this task but I want to know the pros and cons of starting run long running tasks in a background thread in Azure functions.

like image 397
JRun Avatar asked Jan 28 '23 05:01

JRun


2 Answers

It might be best to have an Azure Function running TaskA and have it post a message in a ServiceBus which would trigger another Azure Function running TaskB when something is posted in that ServiceBus since no answer is needed anyway.

Here is the example shown on microsoft's website:

[FunctionName("FunctionB")]                    
public static void Run(
    [ServiceBusTrigger("myqueue", AccessRights.Manage, Connection = "ServiceBusConnection")] 
    string myQueueItem, 
    TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    MethodB();
}

In that situation, you do not have to start a new task. Just call MethodB().

That will give you the flexibility the adjust the Plan of your Azure Functions (App Service vs Consumption Plan) and minimize the overall cost.

like image 62
Kzrystof Avatar answered Jan 30 '23 18:01

Kzrystof


Depending on how complex your scenario is, you may want to look into Durable Functions. Durable Functions gives you greater control over a variety of scenarios, including long-running tasks.

like image 23
Marie Hoeger Avatar answered Jan 30 '23 18:01

Marie Hoeger