'Azure function instances and synchronization

I have an Azure function implemented using C#.

The code support 3 different actions that the user can choose from by setting a field in the request to the function.

My code currently have 3 methods which all use a shared boolean flag which was written with the thought that only a new function's instance runs every time:

public class MyMainClass
{

 public bool flag = true;

 public int Method1()
 {
     while(flag)
     {
        ... somewhere here change the flag to false
     }
 }
 
 public int Method2()
 {
     while(flag)
     {
        ... somewhere here change the flag to false
     }
 }
}

My question is if when using an Azure function, do I need to take care of protecting the flag variable when several requests arrive at the same time and one request may cause an unwanted change in the flag for another? Or a new instance is created for each call and then there's no such danger?



Solution 1:[1]

There is excellent guidelines regarding parallel invocations:

Each instance of the function app, whether the app runs on the Consumption hosting plan or a regular App Service hosting plan, might process concurrent function invocations in parallel using multiple thread.

So, regarding your question:

My question is if when using an Azure function, do I need to take care of protecting the flag variable when several requests arrive at the same time and one request may cause an unwanted change in the flag for another?

I'd say yes, you have to make sure your logic is thread safe. Also do mind that multiple function instances may be involved so different instances may have different values of flag.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Bons