0

I have a question regarding Async methods, return and using statements I could not find an answer to.

Having the following Two blocks of Code. Would both behave the same way? Is there any risk in using Option 1?

Option 1:

public async Task<IEnumerable<Devices>> GetPreviousDevicesAsync(string token)
    {
        IEnumerable<Devices> devices;

        using (var connection = _dbConnectionFactory.CreateConnection())
        {
            devices = await connection.FindAsync<Devices>(statement => statement
                .Where($"{nameof(Devices.Token)} = '{token}');
        }

        return devices;
    }

Option 2:

 public async Task<IEnumerable<Devices>> GetPreviousDevicesAsync(string token)
    {
        IEnumerable<Devices> devices;

        using (var connection = _dbConnectionFactory.CreateConnection())
        {
            devices = await connection.FindAsync<Devices>(statement => statement
                .Where($"{nameof(Devices.Token)} = '{token}');

            return devices;
        }            
    }

I Was wondering if somehow Option 1 code block would keep the connection open as the task would complete after the using block has been left.

Hope you can help with that.

Thanks!

1
  • 4
    since you are calling await, the task would complete inside the using statement in both cases. Both will work the same way. Commented Mar 8, 2019 at 14:20

2 Answers 2

2

Consider the following code:

public async Task<IEnumerable<Devices>> GetPreviousDevicesAsync(string token)
{
    Task<IEnumerable<Devices>> deviceTask;

    using (var connection = _dbConnectionFactory.CreateConnection())
    {
        deviceTask = connection.FindAsync<Devices>(statement => statement
            .Where($"{nameof(Devices.Token)} = '{token}');
    }

   return await deviceTask; 
}

The code would continue to the await, exiting the using block and disposing of the connection, possibly before the process had been completed.

However as Matt.G says, in both of your scenarios the await is inside the using block, ensuring that the connection is not disposed until the task completes, so both will be the same.

Sign up to request clarification or add additional context in comments.

Comments

2

You are calling await, in both cases you will retrieve the result before the connection closes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.