Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# web api condition to check if same function was called with same params

I have a web api in C#.

There is a function which can be called a few times from client (asynchronized of-course) with same param.

What I need is a way to check if the function was just called with same params and if so, skip some code. (heavy action which there is no need to do it twice)

I tried to add a list to the HttpContext.Current.Appliction, and in the start of the function check if the list contains this param:

  1. If contains - skip it.

  2. If not - add the param to the list and perform the action

at the end of the function, remove the the param from the list.

However, this didn't work as the code is being called from a few different places in the client (asynchronized).

So - sometimes it comes to the "if" line and the param is not in the list yet, but then before it adds the param to the list it reaches the "if" line again from the second call, so the param is not in the list yet, so both of them are "true" and both gets into the if.

    public void DoAction(string param)
    {
        try
        {
            if (HttpContext.Current.Application["CurrentDoActionParams"] == null)
            {
                HttpContext.Current.Application.Add("CurrentDoActionParams", new List<string>());
            }
            if (!((List<string>)HttpContext.Current.Application["CurrentDoActionParams"]).Contains(param))
            {
                ((List<string>)HttpContext.Current.Application["CurrentDoActionParams"]).Add(param);
                //.....
                //do heavy action here
                //.....
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (HttpContext.Current.Application["CurrentDoActionParams"] != null)
            {
                if (((List<string>)HttpContext.Current.Application["CurrentDoActionParams"]).Contains(param))
                {
                    ((List<string>)HttpContext.Current.Application["CurrentDoActionParams"]).Remove(param);
                }
            }

        }
    }

Is there a way to achieve this? What is the correct way?

like image 237
Batsheva Avatar asked Feb 27 '26 11:02

Batsheva


1 Answers

Can you implement a cache, and set a suitable expiration option?

Your action can then check the cache to see if the item already exists and return it; if not present it can perform the necessary actions to generate a fresh item for the user, then add it to the cache.

like image 154
Michael Avatar answered Mar 02 '26 02:03

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!