Search code examples
c#.netwcfasync-awaitsimple-injector

unable to use Async await in calling soap service


I am trying to implement a async await in my web application for calling a soap service. I have dependency injection implemented which works fine when i make calls to the database. When i try calling the webservice i get the response but once it exists the query it's a deadlock. I am not able to figure out what's going wrong. I am new to this async stuff appreciate your inputs on this. This is the way i am calling the services in a mvc application to invoke the call

public void GetPersonData()
{
    var persons = queryProcessor.Process(new GetPersonsWhichNeedApiCalls());
    var watch = System.Diagnostics.Stopwatch.StartNew();
    // the code that you want to measure comes here
    SearchAPI(persons).Wait();
    watch.Stop();
    var elapsedMs = watch.ElapsedMilliseconds;
}

private async Task SearchAPI(IEnumerable<Person> persons)
{
    var tasks = persons.Select(async eachPerson =>
    {
        var result = await asyncQueryProcessor.ProcessAsync(new PersonSearchCall { Name = eachPerson.Name, Id = eachPerson.Id });
        commandProcessor.Process(new CreatePersonSearch()
        {
            PersonSearch = result
        });
    });
    await Task.WhenAll(tasks);

}

query:

namespace Sample.AsyncQueries
{
    public class PersonSearchCall : IQuery<PersonSearch>
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }

    public class PersonSearchCallHandler : IAsyncQueryHandler<PersonSearchCall, PersonSearch>
    {
        private readonly IQueryProcessor queryProcessor;
        private readonly ICommandProcessor commandProcessor;

        public PersonSearchCallHandler(ICommandProcessor commandProcessor,
            IQueryProcessor queryProcessor)
        {
            this.queryProcessor = queryProcessor;
            this.commandProcessor = commandProcessor;
        }

        public async Task<PersonSearch> HandleAsync(PersonSearchCall query)
        {
            var client = new PersonServiceSoapClient();

            var personResponses = await client.PersonSearchAsync(inputs).ConfigureAwait(false);
            //Build the person Object 
            return person;
        }
    }
}

This simple injector i was able to achieve this using the synchronous way but as i am calling a list of persons and each call is taking around 2sec. i am trying to leverage the use of async and await to make multiple calls from the list.


Solution

  • As StriplingWarrior commented, your problem is that you're blocking on async code. You need to use async all the way:

    public async Task GetPersonData()
    {
      var persons= queryProcessor.Process(new GetPersonsWhichNeedApiCalls());
      var watch = System.Diagnostics.Stopwatch.StartNew();
      await SearchAPI(persons);
      var elapsedMs = watch.ElapsedMilliseconds;
    }