HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Am I using async C# correctly?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
asynccorrectlyusing

Problem

I have the following bit of code the calls out to two different command line components (each wrapped in their own Task)

public async Task RasterizeAllPdfs(IEnumerable targetUris, FileInfo destination = null)
{
    // rasterize uris to files in the rasterizedOutput directory
    await rasterize(rasterizedOutput.Value, targetUris); 
    // concatenate all pdfs in this directory
    return await concatenatePdfs(rasterizedOutput.Value.EnumerateFiles("*.pdf"), destination);
}


What I would like is for the method to return a task immediately and for the returned task to become resolved once the task returned by concatentatePdfs finishes running.

It seems to work correctly (as in it's returning correct output) but I'm not 100% sure that I'm using the async and await keywords properly

Solution

You are using async/await absolutely correctly, that's how they were supposed to be used.

Please note that from this code it's hard to tell whether the method will return the Task immediately, since it will be waiting synchronously for rasterize method to return the Task, and thus the answer depends on the implementation of rasterize.

As a side note - you are using implicit dependency here (first method prepares files in folder, and second method enumerates all pdf files there). I would prefer explicit dependency: rasterize to return a collection of FileInfo objects consumed by the concatenatePdfs method.

Context

StackExchange Code Review Q#21078, answer score: 7

Revisions (0)

No revisions yet.