0

I'm currently doing a mock voting app using ASP.NET Core 7 Web API and Blazor WebAssembly, I still do not have database for this, so what I did is I use AddSingleton for my repository, for me to test this.

Here's our model:

public class Candidate
{
    public int Id { get; set; }
    public string? CandidateName { get; set; }
    public int VoteCount { get; set; }
}

which has this data

1 John Doe 
2 Max Smith
3 Mark Spencer

Now here's my code on doing a vote.

Here's my repository code:

public void VoteCandidate(int id)
{
    Candidate candidate = _candidates.FirstOrDefault(a => a.Id == id);

    if (candidate != null)
    {
        int currVote = candidate.VoteCount;
        candidate.VoteCount = currVote++;
    }
}

Here's my API code

[HttpPut]
public IActionResult SubmitVote(int id)
{
    _voteRepository.VoteCandidate(id);
    return Ok(_voteRepository.GetCandidateById(id));
}

We tried this and it's working fine, but when we tried to vote at the same time for Max Smith, the vote only returns 1.

Is there a way to handle a simultaneously call in API? Sorry we are all beginners when it comes to this, I hope you can help us.

Thank you.

4
  • Consider a lock: learn.microsoft.com/en-us/dotnet/csharp/language-reference/… or thread safe increment: learn.microsoft.com/en-us/dotnet/api/… Commented Apr 16, 2024 at 1:25
  • Where is your api being "served" from? Are your web assembly clients calling out to a shared api? Commented Apr 16, 2024 at 2:48
  • @topsail no, I'm just creating a mock voting so the 1 web assembly project is the one who calls the web api, we tried to test it on separate machine and vote on the same time, and there the count is just 1, if we vote again on the same time it's 2. Commented Apr 17, 2024 at 0:28
  • Its a little unclear but it seems to me that in "testing" on two machines, you just have two separate, independent applications, each with their own vote counting. They have nothing to do with each other, so it makes no difference what you do at the same time or not at the same time. You need a shared api that both machines call out to ... the vote storage and incrementing of votes has to happen on the api/server side. Commented Apr 17, 2024 at 12:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.