Assume I'm using the following C# Minimal API endpoint:
private Calculator calcObj = new Calculator ();
app.MapGet("/calc", (int a, int b) =>
{
var additionResult = calcObj.Addition(a, b);
var multiplicationResult = calcObj.Multiplication(a, b);
return Results.Ok(new Message() { Text = "Result for addition: " + additionResult.ToString() + "Result for multiplication: " + multiplicationResult.ToString() });
});
This can be called by thousands of users at the same time.
So if the first user calls the API with a=1, b=2 and the second user calls it with a=3, b=4 and the next user with ... and so on...
How is every user getting their personal result without getting the calculation result "destroyed" by the next user's input?
I know the .NET runtime uses a thread pool to manage threads. When a request comes in, a thread from the pool is assigned to handle it. Then it should theoretically be no problem, right?
Or do I have to implement some locking mechanism?
Remark: the MyCalculator
is not using a database. It is built of structs and classes and C# data types only.
UPDATE: To make it more clear assume the calculator does the following (I know the members are not needed, just to dicuss the problem):
using System;
class Calculator
{
private double A;
private double B
public double Addition(a, b)
{
A=a;
B=b;
return A+B;
}
public double Multiplication(a, b)
{
A=a;
B=b;
return A*B;
}
}
In the current code Minimal API handler will use the captured shared instance of the calculator (via the lambda closure mechanism). Since the calculator is not stateless (it mutates internal state) then you will have all sorts of concurrency issues here unless you will do proper synchronization. So you have following options:
app.MapGet("/calc", (int a, int b) =>
{
var calc = new Calculator();
var additionResult = calc.Addition(a, b);
// ...
});
Calculator
as Scoped/Transient (depending on the need, Scoped
will result in an instance shared per scope, which for handler is equal to the request) and resolve it in the handler : app.MapGet("/calc", (int a, int b, Calculator c) => ...