Call WebMethod asynchronously using semaphore and timeout in C#

Viewed 332

I am new to web based C# programming and asynchronous WebMethod calling. I have read couple of articles but does not find any effective way.

What can be done if I have 100's of web service method call and I want to call asynchronously 10 methods simultaneously among them. Wait for 5000 milliseconds for each WebMethod to response, provide timeout if response does not arrive in 5000 milliseconds and based on the semaphore releases from that 10 calls, I will call new methods from rest of the WebMethod.

what is the best way to implement this kind of scenario?

Sample: I have shown 1 sample method only, but this way I have to call 100s of methods asynchronously.

     SemaphoreSlim Semaphore = new SemaphoreSlim(0,10);
    
    //Register method
    soapClient.MethodNameCompleted += soapClient_MethodNameCompleted;
    
    //Call method async
    MethodNameAsync();
    Semaphore.Wait()
    
//This method calls only when WebMethod send a response
    void soapClient_MethodNameCompleted(object sender, MethodNameCompletedEventArgs e)
            {
                string result = e.Result.ToString();
                Semaphore.Release();
            }
1 Answers

May be middleware help you. For example:

public class SemaphoreMiddleware
{
    private readonly static SemaphoreSlim semaphore = new SemaphoreSlim(10, 10);

    private readonly RequestDelegate nextMiddleware;

    public SemaphoreMiddleware(RequestDelegate nextMiddleware)
    {
        this.nextMiddleware = nextMiddleware;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        await semaphoreSlim.WaitAsync(stoppingToken);
        try
        {
            await nextMiddleware(httpContext);
        }
        finally
        {
            semaphore.Release();
        }
    }
}

ASP.NET Core Middleware https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1

Related