0

I have some code that is working fine but I don't understand why. My method performs some SQL operations using the ExecuteReaderAsync, ExecuteNonQueryAsync, and WriteToServerAsync. WriterToServerAsync is the last one I call.

I originally wrote the method with the signature public async void Run() but the Hangfire job runner I am using won't accept async unless it returns a Task. I changed the signature to async Task Run() and then tried to figure out how to return a Task from the method.

I thought that I could just return the same task that was being returned from WriteToServerAsync but this would not compile. I ended deleting the return statement altogether. The compiler does not complain and the method works fine.

public async Task Run()
{
    // Start querying the source first as it is the slowest operation...
    var sqlSourceConnection = new SqlConnection(sourceConnectionString);

    // The query is kind of slow so it needs more than the default 30 second timeout...
    var sqlSourceCommand = new SqlCommand(SourceDataSql, sqlSourceConnection) { CommandTimeout = 180 };

    sqlSourceConnection.Open();

    // Query the records from the source...
    var querySourceDataTask = sqlSourceCommand.ExecuteReaderAsync();

    // Delete existing records from target to make way for the new set...
    var sqlTargetConnection = new SqlConnection(targetConnectionString);

    sqlTargetConnection.Open();
    var sqlTargetTransaction = sqlTargetConnection.BeginTransaction(IsolationLevel.ReadCommitted);

    var deleteRowsTask = sqlDeleteCommand.ExecuteNonQueryAsync();

    // Wait for the delete and query tasks to finish before attempting the bulk copy...
    await Task.WhenAll(deleteRowsTask, querySourceDataTask);

    await sqlBulkCopy.WriteToServerAsync(querySourceDataTask.Result);
}

Why does this compile and work without a return statement for the Task?

Matthew MacFarland
  • 2,413
  • 3
  • 26
  • 34
  • 1
    This is the basics of [how async/await works](http://stackoverflow.com/questions/14177891/can-somebody-please-explain-async-await). – H H Dec 26 '16 at 17:14
  • This guy has very good blog, where you can find a lot of interesting stuff about async/await. And more:) http://blog.stephencleary.com/ – Sasha Dec 28 '16 at 11:35

1 Answers1

4

Why does this compile and work without a return statement for the Task?

Because the return type Task is the equivalent of void (a method that doesn't return any value) for an asynchronous method that can be awaited.

Please refer to the following links for more information about the async/await keywords in C#.

Async/Await - Best Practices in Asynchronous Programming: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Asynchronous Programming with async and await (C#): https://msdn.microsoft.com/en-us/library/mt674882.aspx

mm8
  • 163,881
  • 10
  • 57
  • 88