Best Practice with C#. Is it okay to pass parameters with await?
UPDATE: This question was the subject of my blog in March 2020. See it for more discussion of this issue. Thanks for the interesting question!
I'm going to assume here that you intended that to be a function call as the sole member of the argument list.
As others have noted, there is no difference between
x = M(await FAsync());
and
var f = await FAsync();
x = M(f);
And that is the same as
var ftask = FAsync();
x = M(await ftask)
So it doesn't matter which way you write it, correct?
Give that some thought.
In that specific scenario all three workflows are the same. But there is a potential difference here if we only slightly vary the scenario. Consider:
x = M(await FAsync(), await GAsync());
This is the same as
var f = await FAsync();
var g = await GAsync();
x = M(f, g);
and what do we know about this workflow? The GAsync task is not started until the FAsync task is finished! But it looks like there is an opportunity for having two tasks going at the same time here, which might use the current thread more efficiently! Likely the workflow would be better written as:
var ftask = FAsync();
var gtask = GAsync();
x = M(await ftask, await gtask);
Now FAsync and GAsync tasks both start, and we do not call M until both finish.
My advice is to think carefully about where you put your awaits. Remember, an await is intended to be a point in an asynchronous workflow where the workflow asynchronously pauses until a precondition of the continuation is met. If you can delay awaiting a task until it is actually a precondition, you might be able to eke out a performance win.
There is no runtime difference between;
var results = MapResults(await GetDataAsync())
and
var tmp = await GetDataAsync();
var results = MapResults(tmp)