Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice with C#. Is it okay to pass parameters with await?

Tags:

c#

.net

Is it okay to pass parameters, with await? what are the PROS and CONS of doing this?

var results = MapResults(await GetDataAsync());
like image 450
Drew Aguirre Avatar asked Mar 06 '20 03:03

Drew Aguirre


People also ask

Where can I practice C problems?

CodeChef discussion forum allows programmers to discuss solutions and problems regarding C Programming Tutorials and other programming issues.

Is C still useful to learn?

Though practically ancient in computer science terms, C and C++ remain two of the most popular programming languages in use today. These languages have laid the foundation for many other languages and are great options for starting your coding journey.


2 Answers

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.

like image 70
Eric Lippert Avatar answered Nov 15 '22 15:11

Eric Lippert


There is no runtime difference between;

var results = MapResults(await GetDataAsync())

and

var tmp = await GetDataAsync();
var results = MapResults(tmp)
like image 31
Jeremy Lakeman Avatar answered Nov 15 '22 14:11

Jeremy Lakeman