1
i have to increment a column in the database and this increment may depend on the situation, for example increment according to the user, I am using Jmeter to send 100 requests at the same time, but all of them are running at once, at the time of saving I needed to make a logic to increment the value of the column I tried to use lock and Semaphoreslim, but when sending the requests the server is stopped and does not execute anything when it arrives in lock or _Semaphore. Wait() requests do not pass, I am using Nhibernate, how can I make this type of function block part of a method to be executed once each.
private static readonly object _lock = new object();
public override DepositoProduto Save(DepositoProduto entity)
{
lock (_lock)
{
using (var transaction = Session.BeginTransaction())
{
//aqui a função do auto incremento pode depende no caso coloquei um exemplo simples
entity.Codigo = All().OrderByDescending(x = > x.Codigo).Select(x = > x.Codigo).First() + 1;
//aqui realiza o save no banco
transaction.Commit();
}
}
return entity;
}
Using Semaphoreslim
private static SemaphoreSlim _semaphore = new SemaphoreSlim(1);
public override DepositoProduto Save(DepositoProduto entity)
{
_semaphore.Wait();
using (var transaction = Session.BeginTransaction())
{
//aqui a função do auto incremento pode depende no caso coloquei um exemplo simples
entity.Codigo = All().OrderByDescending(x = > x.Codigo).Select(x = > x.Codigo).First() + 1;
//aqui realiza o save no banco
transaction.Commit();
}
_semaphore.Release();
return entity;
}
Are you using thread?
– Maniero
No, the method is an Actionresult that method " override Depositoproduct Save" is called at the end of Actionresult before return
– Fernando josé
Then there is no reason to synchronize methods, if the execution is not concurrent there is no problem. If the problem comes from elsewhere, it’s architecture error, not code error. This code is full of complications for zero benefit, probably trying to fix an error that came from another wrong decision.
– Maniero
Well, it is practically concurrent yes, because arrive several requests in Actionresult and all are executed at the same time
– Fernando josé
There is virtually no competitor, or is or is not. If you are not using thread so it’s not. Data access can be concurrent and that’s database handle problem, you just need to set it up correctly. I don’t know if nhibernate has any tool to help with this. For complex solutions it is not useful. But I don’t even know if you have any complex solutions, if you’re having any problems, but if you are, it seems to be an isolation problem.
– Maniero