gdp
gdp

Reputation: 8232

Limiting asynchronous requests without blocking

i am after some advice/strategy on limiting http requests when consuming multiple web services. I feel i could do this if the requests were happening synchronously, but they are asynchronous and think i should try to perform the limit logic in a way that i wont block.

Due to the web app consuming multiple web services there will be different limits for different requests. I was thinking something like this, but aren't sure how to proceed in a no blocking manner:

request method:

public static Task<string> AsyncRequest(string url, enum webService)
{
    using(LimitingClass limiter = new LimitingClass(webService))
    {
       //Perform async request
    }
}        

In the LimitingClass it will have logic like checking the last request for the given webservice, if it violates the limit then it will wait a certain amount of time. But in the mean time if another request comes in to a different webservice then i dont want that request to be blocked while the LimitingClass is waiting. Is there anything fundamentally wrong with the above approach? Should i open up a new thread with each LimitingClass instance?

Some pseudo code would be great if possible.

Many Thanks

UPDATE:

This is a simplified version of my current request method:

public static Task<string> MakeAsyncRequest(string url, string contentType)
{
    HttpWebRequest request = //set up my request

    Task<WebResponse> task = Task.Factory.FromAsync(
        request.BeginGetResponse,
        asyncResult => request.EndGetResponse(asyncResult),
        (object)null);

    return task.ContinueWith(t => ReadCallback(t.Result));
}

I just want to wrap this in a using to check the limits and which doesnt block other requests.

Upvotes: 1

Views: 553

Answers (1)

Evgeni
Evgeni

Reputation: 3343

So how are you limiting an access to resource without blocking ?

I think you need to look at Semaphores - they allow to limits the number of threads that can access a resource or pool of resources concurrently.

Upvotes: 1

Related Questions