简体   繁体   中英

Multiple Requests in Web Api gets an exception when calling WCF service

The company which I work has implemented .Net Web Api 2 recently and I'm responsible for it. I'm facing a problem that I couldn't resolve.

There's a Post method which consumes a WCF service. This WCF executes in around 30 seconds and enumarates a few lists that I passed as request. So I've read about concurrency when calling Web Api methods and got scared. However I did implemented IHttpActionResult as result type of all my ApiControllers. In that implementation I''ve done as everybody recommends return a Task. Nevertheless the exception still happens. This exception is generic and to me is clearly a concurrency between two threads. Below I'll show you a piece of code.

UPDATE

Generic means that I'm getting different exceptions all the time. Because concurrency could happen everywhere.

public IHttpActionResult Post([FromBody]Cotacao cotacao)
{
    return new CotacaoResult(cotacao, Request);
}

public abstract class ActionResult<T> : IHttpActionResult where T : class
{
    protected T Item { get; private set; }
    protected HttpRequestMessage Request { get; private set; }

    protected ActionResult(HttpRequestMessage request)
    {
        Item = null;
        Request = request;            
    }

    protected ActionResult(T item, HttpRequestMessage request)
    {
        Item = item;
        Request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Do());
    }

    private HttpResponseMessage Do()
    {
        try
        {
            return Execute();
        }
        catch (Exception)
        {
             return new HttpResponseMessage(HttpStatusCode.InternalServerError) { RequestMessage = Request };                
        }
    }

    protected abstract HttpResponseMessage Execute();
}

public class CotacaoResult : ActionResult<Cotacao>
{
    public CotacaoResult(Cotacao item, HttpRequestMessage request) : base(item, request) { }        

    protected override HttpResponseMessage Execute()
    {            
        using (var gateway = new GatewayClient()) //WCF Service
        {
            var result = gateway.CreateQuote(Item.ToQuote());

            //Something else
        }
    }
}

My question is : How can I deal with concurerncy in Web Api when it cosumes a WCF and there're a lot of requests at the same time?

I had it resolved. There was a static class at wcf layer which was concurring with other threads. I just made it non-static.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM