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?