Fiona
Fiona

Reputation: 1599

calling WCF method asynchronously

I'm looking for feedback on the following code. I've read here that I should avoid use of async void.

So as a result I've implemented the following in a method..

foreach (var sample in returns)
{
    _logger.Debug("Calling async method");
    var resultFromMethodCall = CallMethodAsync(uploadReturn);
    _logger.Debug("Continuing....");

}




async Task<Tuple<bool,long>> CallMethodAsync(Sample sampleReturn)
{
    try
    {
        Service1Client client = new Service1Client();
        Tuple<bool, long> results = await client.ValidateSampleReturnAsync(sampleReturn);
        _logger.Debug("call to Sample Return validator completed for sample: {0}", results.Item2);
        return results;
    }
    catch (Exception ex)
    {
        _logger.Error(ex, "Error occured while calling WCF service");
        return new Tuple<bool, long>(false, sampleReturn.Id);
    }
}

When I do nothing with the returned variable resultFromMethodCall, the logging indicates the all is working as I expect. However when I log out items from the variable resultFromMethodCall, it appears that its now running synchronously as it waits for the object to be returned from the call.

Am I missing something obvious here? Or am I completely misunderstanding how this works.

Upvotes: 0

Views: 259

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 457227

However when I log out items from the variable resultFromMethodCall it appears that its now running synchronously as it waits for the object to be returned from the call.

If you're using resultFromMethodCall.Result to get the items, then yes, it's blocking and running synchronously.

If you're using await resultFromMethodCall to get the items, then no, it's not running synchronously. However, it is running sequentially - meaning that the method will "pause" at the await and only continue when the resultFromMethodCall task completes.

Upvotes: 0

usr
usr

Reputation: 171246

CallMethodAsync is correct.

If you don't await (or Wait) resultFromMethodCall execution will continue while that task is still running. Whether you should allow that depends on what you want to happen.

Upvotes: 1

Related Questions