Should You Use The Async Suffix in C#?

  Рет қаралды 62,706

Nick Chapsas

Nick Chapsas

6 ай бұрын

Use code EF20 and get 20% off the brand new "Entity Framework Core in .NET" course on Dometrain: dometrain.com/course/from-zer...
Use code GRPC20 and get 20% off the brand new "gRPC in .NET" course on Dometrain: dometrain.com/course/from-zer...
Become a Patreon and get special perks: / nickchapsas
Hello everybody, I'm Nick, and in this video, I will talk about using the Async suffix for asynchronous methods in C# that are meant to be awaited.
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: github.com/Elfocrash
Follow me on Twitter: / nickchapsas
Connect on LinkedIn: / nick-chapsas
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер: 373
@sunefred
@sunefred 6 ай бұрын
I am a strong believer in idiomatic code, that is: - Follow the language conventions based on the language - Follow the language conventions for your team or organization If you do this, your team can focus more on coding and less on reading code. I think some also call this "The Law of Least Surprise". So, for me, Async suffix stays for C#.
@fredrikjosefsson3373
@fredrikjosefsson3373 6 ай бұрын
Whatever project I work with, I follow the convention of the project even if I personally dislike it. Then of course you can have a talk with the team and decide to stop using a specific convention and start renaming when you are doing something in a certain class. But I agree, its easier for the team if we dont make major changes
@rtl6832
@rtl6832 5 ай бұрын
My thoughts exactly. Unfortunately, some developers are opinionated and want to impose their own designs regardless.
@Black-Dawg-Jesus
@Black-Dawg-Jesus 5 ай бұрын
@@fredrikjosefsson3373 "I follow the convention of the project even if I personally dislike it." This. There is only one thing worse than a bad codebase, and that is an inconsistent codebase. If, let's say, a shitty naming pattern drags out across the entire projects, even if I dislike it, I at least know what I have to expect.
@Baby4Ghost
@Baby4Ghost 5 ай бұрын
100% agree on all points. Conventions and standards are key.
@BRelding92
@BRelding92 5 ай бұрын
@@rtl6832 Some code is trash and should not exist, though. Sometimes it is unreadable, ineffecient, not easy to adapt, or insecure/unsupported. 1 rewrite will save developers countless hours down the line, not to mention the benefits to the customer and users in regards to security and performance.
@Palladin007
@Palladin007 6 ай бұрын
I use the async suffix for three reasons: * Habit, I add it almost automatically * Convention, I always try to stick to the most common convention * It helps me to recognize whether it is async or not. If it's not there, it interferes with my writing flow, because I only realize that I have to await it at the second moment. Once this was also a bug that I wouldn't have had with an async suffix.
@petedavis7970
@petedavis7970 6 ай бұрын
Agreed and when working with clients we usually try to get them on board with that and raise it in code reviews. For me, your final point is really the reason for doing it. Especially when coupled with var. var x = GetWhatever(); Is x a Task or the return of GetWhatever()? Well, if Async in the suffix isn't in my coding standards, I don't really know. I mean, the tools (VS, VS Code) do make it pretty easy to know, but when you're looking at it, say in github or some other non-IDE environment, it's far less obvious.
@magashkinson
@magashkinson 6 ай бұрын
You can recognize that the method is asynchronous by its signature
@Palladin007
@Palladin007 6 ай бұрын
@@magashkinson Not during autocomplete, which is very important to me.
@megasuperlexa2
@megasuperlexa2 5 ай бұрын
@@Palladin007 but the compiler is on your side and you should have seen its warnings (even if you do not use IDE in even its simplest form like neovim+lsp)
@BeatsByYari
@BeatsByYari 6 ай бұрын
If you have a new(er) code base where most things are async, I don't think you need to use it. For bigger/legacy codebases that mix sync and async together you should use it for clarity because you might not realize immediately that a method is async.
@BigMaaaaaaan
@BigMaaaaaaan 6 ай бұрын
I agree. For newer code base adding Async suffix is redundant. At this point it is like Hungarian Notation. Obsolete.
@FrancoisNel256
@FrancoisNel256 6 ай бұрын
You do not review PRs if you say that....
@simonlester4316
@simonlester4316 6 ай бұрын
I never use the Async suffix personally for my own code-base. However, if there are defined coding guideline being implemented, I tend to adhere to it. But preferably, I don't like to use them.
@lowds
@lowds 6 ай бұрын
I always use the Async suffix, it’s more there to help people calling my code rather than to help me while I’m writing the code. If you see a method ending in Async then it (probably) returns a Task
@fifty-plus
@fifty-plus 6 ай бұрын
If it is probably, that's a problem. Anything that can eliminate a code review debate, like use the suffix everywhere or don't use it is a better day for everyone.
@shadmansudipto7287
@shadmansudipto7287 6 ай бұрын
​@@fifty-plusthat was a figure of speech I'm guessing.
@Bliss467
@Bliss467 6 ай бұрын
@@fifty-plusI assume the case where it doesn’t return a Task, it returns IAsyncEnumerable or something else of the sort.
@NickSteffen
@NickSteffen 6 ай бұрын
@@Bliss467 yea or a valuetask, or anything that is awaitable.
@lowds
@lowds 6 ай бұрын
@@fifty-plus in my code it's always returning a Task :) 'Probably' was more of a caveat just because there are some really old APIs out there from back before async-await was a thing, where the method names end in Async but they do not return a Task - going back to .NET 1.1, or .NET 2.0 when a different async pattern was used. But your point is valid, any code that me or my team writes where the method name ends in Async but doesn't return a Task would be highlighted in code review.
@YungDeiza
@YungDeiza 6 ай бұрын
I think you should only use it if there is a corresponding synchronous method. It's quite easy to look at the return type and the IDE will also warn you.
@_xentropy
@_xentropy 5 ай бұрын
This.
@allinvanguard
@allinvanguard 6 ай бұрын
I tend to not use it because I mainly work in an environment where basically everything is async all the way. So it's essentially the "default" which would otherwise be sync. I could imagine that it is useful in a very cpu bound sync based repository though. Stick to the habit of the repo I think.
@Bliss467
@Bliss467 6 ай бұрын
You’ll still end up with a lot of methods that aren’t, like utility methods or mappers, etc
@AcidNeko
@AcidNeko 6 ай бұрын
@@Bliss467 IDE will complain if task is not awaited, and utility/or static methods mostly don't have async overloads
@allinvanguard
@allinvanguard 6 ай бұрын
@@Bliss467 Sure, but then again, if you remember a few years ago we had the Hungarian notation as a de facto standard for variable naming. Everyone moved away from it and also adopted var entirely, because IDE support made it very easy to see what type you are dealing with. In that regard I don't see why we would still need a semi-hungarian style of handling the "function color"
@neverknowsbest2879
@neverknowsbest2879 6 ай бұрын
​@@allinvanguard "also adopted var entirely" No. "because IDE support made it very easy to see what type you are dealing with" Quite often people read code outside of IDE. During code review for example. And even in IDE you need to hover over var for IDE to show the type, it makes reading harder. Personally I use var only when it is obvious from the first glance what the type is. For example var textList = new List(); but never when it is not obvious. For example List textList = _someMagicDependency.GetTextList(); Usually programmers spend much more time on reading code than writing it. It is better to lose more time on writing but write more understandable code.
@adambickford8720
@adambickford8720 6 ай бұрын
@@neverknowsbest2879 no. Adding superfluous types just makes it harder to maintain as it reduces the signal to noise ratio. It also helps you if you have a `List` but you're really treating it like an Enumerable or whatever. The compiler is likely smarter than you are. Just say you're old.
@SeMDesu
@SeMDesu 6 ай бұрын
I don't use it in "newer" code. People say that callers will know that the method is async, so that's why they use it - it takes a second to check if the method returns Task or not, also if you are not familiar with the method, you will check the return type anyways (just to be sure, it's not like it takes your time).
@josefromspace
@josefromspace 6 ай бұрын
Another good video. I agree with the approach here presented. As mentioned by many, it helps the Code Review process.
@wesplybon9510
@wesplybon9510 6 ай бұрын
Before watching the video, this is my rule: If we need an async and synchronous version of the same method, for whatever reason, it gets the Async suffix for clarity. Otherwise VS does a pretty good job letting you know when you're using an async method improperly. I don't use the suffix that often :) Post Game Analysis: Yea... I rarely use it. In the same way variable type prefixes rode off into the sunset, indicating how a method should be used in its name is unnecessary. Modern IDEs will tell you how it should be used. If you're not using a modern IDE to write C# then... wut why? It's literally FREE. The only benefit I see to using it is to differentiate between sync and async methods that do the same thing. At that point, you're not describing how to use the method, but what the method does. I can hear some people saying, "yea, but having Async there tells you what the method does anyway." While this is true, the minutiae of the inner workings of a method are rarely important enough to take up method name real estate. You wouldn't mention in your method name whether or not your using an iterator or an indexer based approach for looping through a list, right? All of that should remain behind the method name unless it has value in presenting to the user. Now, maybe I would think differently if my company did anything else aside from in-house software. Maybe if we were releasing libraries for public consumption we'd enforce a different standard.
@jcampos
@jcampos 6 ай бұрын
Note that calling a method returning a Task (or another awaitable) *without* await is perfectly valid and sometimes desirable and can be easily mistaken (specially for methods returning Task), so an IDE shouldn't tell you you shouldn't do it. Having the suffix allows you to reason "at first glance" that a method should be awaited (and if it isn't, then you can follow the code to see if there's something done with the returned task or not and see if it's a mistake)... when you have no suffix, you have no "initial way of seeing it at a glance", no matter the IDE you use.
@josefromspace
@josefromspace 6 ай бұрын
Another objection could be that not all your code will be read through an IDE, i.e. a Pull Request.
@jcampos
@jcampos 6 ай бұрын
@@josefromspaceI agree (see my comment somewhere around here where I specifically say that), but even within an IDE, calling a method returning an awaitable without awaiting on it is perfectly valid and no IDE (at least, not without further static analysis of what you do with the return value) should warn you about doing so
@josefromspace
@josefromspace 6 ай бұрын
@@jcampos Yes, this is true.
@rapzid3536
@rapzid3536 6 ай бұрын
@@jcampos Si, same with TypeScript and they have rejected adding warnings/errors for this. There are a slew of eslint rules that can cover certain scenarios but they are rarely, IMHO, used because it's so use-case specific.. And they seem to have rejected any one-size-fits all solution as well.
@KingMotley
@KingMotley 6 ай бұрын
In our big projects, we have an analyzer that will generate a warning if you write an async method that does not also have async appended to the name. Considering how difficult it is to get many developers to await async methods even when it is explicitly called out, I can't imagine ever recommending removing it and seeing even more issues crop up because of it. For that reason, we also have an analyzer that warns if you ever call a method that ends with Async and you do not immediately await it. On the rare occasion that you are going to await it later, then you need to wrap the line in a comment disabling the check with an explanation of why you aren't awaiting it immediately. Also, not everyone reviews code from within the context of Visual Studio, so being able to see these types of issues in a PR's code view is immensely helpful.
@fotispapadopoulos6659
@fotispapadopoulos6659 6 ай бұрын
I would rly love the 2nd analyser that warns you if you don't await an async method. Was it hard to implement??
@dire_prism
@dire_prism 6 ай бұрын
@@fotispapadopoulos6659 The compiler already does that by default :)
@joanpearl7184
@joanpearl7184 6 ай бұрын
I would assume from how I write anything that is async, that if leveraged properly you would be doing this all the times me.
@joshman1019
@joshman1019 6 ай бұрын
Code reviews are an excellent point!
6 ай бұрын
This is a kind of Hungarian notation. If you have your arguments not to use Hungarian notation for the rest of your identifiers, you should face those exact same arguments for this case. I personally cannot find a reason to use the "Async" suffix these days. Not even the overload clash when you have sync/async versions, because you can (and should) always pass the CancellationToken in the async version, thus getting a different signature.
@reikooters
@reikooters 6 ай бұрын
I definitely don't provide a cancellation token parameter on all async methods. For something like writing to a database, if the client's browser disconnects before the server returns the response, that scenario shouldn't cancel the write. If there were no side effects like the method was just selecting data, then yes I'd use it
6 ай бұрын
@@reikooters I would say it's better to cancel the write (it should be safe if it's well implemented) than potentially leaving the connection open for a long time were it be an unexpected problem with the DB operation. But anyways, if you have a case where you don't want cancellation token, and also sync version, then that could be an exception for using "Async" suffix. Although in that case you'd not be using it as Hungarian notation but to work around the overload syntax limitations.
@megasuperlexa2
@megasuperlexa2 2 ай бұрын
@ even in this case, just ignore passed ct (with a meaningful comment) and no exceptions needed ) but I personally think this is an artificial example, th DB writ should be canceled in this case as well
@jorgebranquinho8690
@jorgebranquinho8690 6 ай бұрын
I usually don't use it. Unless I'm working on a project that uses that convention, in that case, it's best to keep consistency. In my opinion, it's perceptible enough: 1) the method returns a task instead of T 2) you'll either await it or store it in a var with the Task suffix or get the awaiter and get the result. So either way it's clear it's an async method. I find that it helps me with reading code more easily than if there are extra words I need to ignore.
@jcampos
@jcampos 6 ай бұрын
Having the async suffix helps me greatly when I'm doing PR reviews (where I don't have an IDE to tell me the signature of the method necessarily, and I don't know the return value of something). Yes, there are other ways to do reviews and online IDEs are better and better every day... but having it at a glance where you don't have any IDE available to you is an advantage... And what you are "saving" by not using it, is absurd (because code IS written with an IDE -not always read with one-, which autofills for you) ... also, habit, and convention And in my case, the habit doesn't come from having "both sync and async APIs", but because I used the TPL when async/await didn't exist, and a method returning "Task" (without seeing the actual "async" keyword -which is also not part of the signature at all and you can only know it if you have access to the actual code-) didn't necessarily mean that it was meant to be awaited (we used "Async" for those methods)... it "could", but the normal use of TPL was vastly different to async/await when those didn't exist (and basically "meant threads", not "just asynchronous"), it was a way of differentiating both ways of "usage"
@adamoneil7435
@adamoneil7435 6 ай бұрын
I use the Async suffix -- due to a lot of "muscle memory" I'd say. I recall the MS guidance you referenced in the video, and that's how it started for me. At my day job they don't use it, so I had to adjust myself a bit for that. I didn't let it bother me, but in my personal/side projects I use the suffix regularly. I like your callout of why controllers and other internally-called methods don't have the suffix -- that makes sense IMO.
@_iPilot
@_iPilot 6 ай бұрын
I don't use Async suffix at all. 99.99% of my code has the only implementation either sync or async. I believe that such approach valid for libraries only. If you are sure that your code can be executed synchronously in some cases (but not always) there is the ValueTask type for you. And it again leads to the only implementation of the method - sync always or Task/ValueTask for async or partially async.
@billy65bob
@billy65bob 6 ай бұрын
I only do it with library code (for consistency with convention) and when mixing new async code into an old codebase. A mixed project is also at constant risk of introducing really nasty deadlocks if the async vs non-async distinction isn't respected, so it's kind of really important. But If it's a new application or service where everything that can be async, is async, then it's just noise and I don't bother. Plus there's the cancellationTokens that get passed into nearly every async method to help set them apart.
@urbanelemental3308
@urbanelemental3308 6 ай бұрын
Generally agree. I wrote an entire lib for accessing various blob storage APIs, and because everything was async (classes were named AsyncXXXXX) and the methods were all ValueTask or ValueTask I simply left out the "Async" suffix because it was redundant. That said, I have written APIs that have methods like `PostAsync` because I wanted to allow for a synchronous version (`Post`).
@LoicMusic
@LoicMusic 6 ай бұрын
Hey @Nick Chapsas! Thanks for you videos. I do put the Async suffix, because the return type Task (or Task) by itself does not carry the information that the returned Task has already started (usually by calling Task.Run at some point) when the call returns, and that the caller can reasonably expect a result from that Task without having to call the Start() method on it. Worst than that, awaiting a non-running task is indefinitely blocking the current thread! This information is lost when we don't explicitly call the method "Async". It is only a matter of convention, because calling a method "Async" does not ensure that the returned Task is running, but it is still a good convention point where humans can understand what they call and how they should implement their methods. For me, the biggest issue here is returning a Task, rather than some type that carries the information that the work has started (like a Future, or something like that). My 2 cents 😅
@VeNoM0619
@VeNoM0619 6 ай бұрын
For personal projects, I use the opposite thought process. UploadData() - async, as that should be the norm, and I don't need backwards compatibility UploadDataWait() - because its blocking and you wait on it, I can't think of a better fitting name like "Blocking", but its a short word, and mostly fitting.
@SysyTube
@SysyTube 5 ай бұрын
in today's async world that's a smart idea
@andreyandreev4636
@andreyandreev4636 6 ай бұрын
Probably it was important to use Async suffix in the past. But now, when 1. a lot of methods are async, 2. when VS and compilers are good enough, I do no see the reason to add such suffix. It just reduces the readability of the code. it is like "never use the variable's type in the variable's name." :) but one reason (for me) is to use Async suff is legacy code to extend interfaces/classes but the same methods but async.
@pablocom
@pablocom 6 ай бұрын
Nowadays async is almost everywhere. Most of the time non-async methods are in domain entities and a couple more places, but that's it. My opinion is that most of the code bases do not benefit from having the Async preffix, for the reader of the code may be repetitive and obvious. For Microsoft's .NET teams it makes more sense I guess... Anyway, few things deserves the word "always" or "never", context is king
@Ristogod
@Ristogod 6 ай бұрын
I stick to the same conventions as Nick. If I have an extension method that extends a Task, then I will forgo the Async suffix. Additionally, my naming syntax is to prefix with Async any method returning an IAsyncEnumerable
@hacinisouleymanboumedyen3881
@hacinisouleymanboumedyen3881 6 ай бұрын
I use it to see the diff because in some cases you need to have same action in both situation Sync and Async.
@sanampakuwal
@sanampakuwal 6 ай бұрын
Since Sync methods are less (most of modern C# codebases). What do you think about removing prefix for Async methods but adding "Sync" for Synchronous method?
@hacinisouleymanboumedyen3881
@hacinisouleymanboumedyen3881 6 ай бұрын
@@sanampakuwal Async/await was first introduced in C# 5.0 in 2012. Before that, actions were only synchronous, and it did not make sense to add Sync to all actions prior to 2012.
@DemoBytom
@DemoBytom 6 ай бұрын
I don't really use the suffix, as I don't tend to have sync and async versions of the method. But even if I did, pretty much all my async methods accept CancellationToken as well, so the method declarations wouldn't be the same between sync and async anyway.
@AMAN-oz8ud
@AMAN-oz8ud 6 ай бұрын
Extremely helpful in PR reviews. If something calls an async method without awaiting, it says that it’s fire and forget kind of call. Without async prefix it’s missed most of the times
@mynameisshadywhat
@mynameisshadywhat 6 ай бұрын
I take the same approach as you. I only use the suffix where its going to be called by a real person. I have a terrible memory so it also helps me remember that i need to await it.
@svetoslav.hadzhiivanov
@svetoslav.hadzhiivanov 5 ай бұрын
I totally agree with your point. I don't use it on Minimal API extension methods either since that's is a func callback.
@xavier.xiques
@xavier.xiques 6 ай бұрын
I use "Async" in the same way as you do, so I totally agree with what you say in the video.
@solidid9368
@solidid9368 6 ай бұрын
The async thing is kind of weird. I don't have a real solution for that. Just my two cents to it: Well, I am doing a lot of code reviews now a days and I often complain about the code that other colleagues are writing. And thats because of that old guideline of microsoft which we agreed to adopt in the team years ago. "Hey dude, you method is async... It has to be named X..Y..Z..Async" Then the dude usually goes through the new code renames everything to ...Async. And honestly that feels odd to me. It doesn't provide any difference but takes a lot of additional changes in the code base. I mean, isn't the signature of the method enough for "users" of it to decide if they want to await it or not? You already tell in the signature that you are returning a Task. The "user" can and should decide if he (or she) wants to await it or not. Another issue I have with the Async suffix is. That you have to define (well name) it in the interface. Interfaces shouldn't know implementation details. And for me doing stuff async within a method is a implementation detail. It shouldn't be present at the interface level. But when we define method names like GetSomethingAsync we are pushing the developers to implement something in a way we shouldn't at interface level. Plus we already define method to return Task instead of T in the interface.
@jimmyzimms
@jimmyzimms 6 ай бұрын
Like many things, it "depends" Our internal use code bases no longer have any blocking code and we've over the years performed major version updates on our internal package feeds and we do not ship code externally, the teams have agreed to drop the suffix as redundant and extra verbiage. Also we all run R# which has had an analyzer for missed awaits forever so ... However if we were publishing external code or mixed IO patterns or something else we'd absolutely keep to the Async convention
@paarma1752
@paarma1752 6 ай бұрын
If I'm creating a shared library, especially with a critical API, I do use Async suffix, because that's the clearest, most explicit way to state what's going on even without an IDE. In application code that I only read inside an IDE I never use Async suffixes. For the sake of being as concise as possible. Just like I use only var for variables and short names for everything. Less characters for the same functionality means less scrolling up and down and left and right, and one is able to understand the big picture with just one glance. One can still hover on things etc use their IDE to dig deeper.
@meirkr
@meirkr 6 ай бұрын
I totally agree with your approach. Async suffix is must for readability except, of course, the special cases like controllers, in which you don't really call them directly.
@garcipat
@garcipat 6 ай бұрын
What do you think of always having cancellationtoken in the signature for async methods? And also if it should have a default value or not.
@kaiserbergin
@kaiserbergin 6 ай бұрын
I never used it until recently. Just makes it more clear and less likely to forget an await.
@MaThMaTa1000
@MaThMaTa1000 6 ай бұрын
For any relatively recent code base, it's not needed at all as everything return tasks by default and can be run asynchronously. The default is now async instead of sync, so now we only add the suffix for "sync" methods as in XyzSync
@alexclark6777
@alexclark6777 6 ай бұрын
I seldom use it. I used to all the time, but started to regard it as a code smell. I know the method is async because it's returning a Task. Exceptions to this rule are if I need a synchronous method alongside the async one, then I distinguish them by name. Similarly if I'm forced to write an async void method for an event handler, I'll suffix that with Async for clarity. But for my own code base, the assumption is "if it's IO it's going to be async" so I don't feel the need to explicitly write that out.
@josefromspace
@josefromspace 6 ай бұрын
How is the approach here presented a code smell? I can understand and respect the preference, but disregarding the use of the suffix as a "smell" is a bit much IMO.
@alexclark6777
@alexclark6777 6 ай бұрын
@@josefromspace Personally, I find it to be an unnecessary descriptor added to a function because I can already tell that it's async without the need for explicitly stating that by naming it as such. It's a bit like suffixing your functions with their return type. I would not name functions "GetAgeInt" or "GetNameString" any more than I would name them "GetCustomerAsync". I get that some people prefer to have the Async suffix for their own purposes though, and that's fine. It's a personal preference of mine and not something I'd fail a peer review over, I just find it more readable without it. 🙂
@codingbloke
@codingbloke 6 ай бұрын
I don't use Async suffix unless there is a genuine reason to also include a synchronous version of the method (very rare). I was finding that nearly everything public was async so there was just a cloud of useless "Async" terms in the code. I'm very keen on careful naming and eliminating noise so that that code describes itself in human terms instead of technical ones where reasonable.
@sanampakuwal
@sanampakuwal 6 ай бұрын
I use Async but I really prefer (wanted to) moving to remove "Async" suffix approach but ecosystem, companies, community as a whole need to move to this new approach to make ecosystem clear and smooth. I'll move when they do!
@ahupond
@ahupond 6 ай бұрын
5:40 Actually the rationale behind the controller methods not using Async suffix was because back in the days aspnet developers could implicitly route their methods by using the verb as the method name without having to decorate them with an attribute. For some time it didn't worked if you added an Async suffix to the method name, that's why people had some async methods named "Post" instead of "PostAsync", and started to drop the Async suffix in controllers. BTW that convention is still used for routing Microsoft OData 8 controllers, although now you can postpend anything to the verb name. Still using the async suffix but can't wait until Microsoft drops the async keyword and suffix in favor of a sync keyword and suffix :)
@renynzea
@renynzea 6 ай бұрын
I would continue to use Async as a suffix. That way I know when I call the method if I need to await it or not (if it is not something I frequently use). I would also take it a step further and add a test to look at every method in the assembly, and if the method returns a task the method name has to end in Async and accept a CancellationToken or it is a standards violation. Then tie that into check-in policies so you can't push to master unless its resolved. But that's me.
@rolf8064
@rolf8064 6 ай бұрын
I would use the suffix by default except: - in a fully async component, to lower code reading complexity - (like you said) in the cases where methods are not called by the developer (UT, controllers...)
@PatricSjoeoe
@PatricSjoeoe 6 ай бұрын
As long as you have more sync code than async, I think it's better with a Async suffix. Actually, we have started to add _Sync suffix for sync version of a method, when we have a Async version to. This to remind the developers that they can replace it when needed.
@eyassh6747
@eyassh6747 6 ай бұрын
Hey Nick, I'm a relatively new C# dev with less than 2 yrs of exprience imo I'd keep using the suffix because it is what I saw when I started to learn about stuff like the MongoDb driver in C# which has a synchronous and an asynchronous Find method for example. Back when I saw this, I thought it was the convention, plus it is harmless to use
@Myuuiii
@Myuuiii 6 ай бұрын
I still like it, although sometimes i tend to forget to add the suffix
@diadetediotedio6918
@diadetediotedio6918 6 ай бұрын
I think just as we have type hints in the editor, we should probably have async hints as well, it is not a hard thing to implement on top of the tooling and will serve the same indication purpose as the async suffix
@7th_CAV_Trooper
@7th_CAV_Trooper 6 ай бұрын
Not everyone is using Visual Studio and you don't only read code in an ide, so use the suffix.
@diadetediotedio6918
@diadetediotedio6918 6 ай бұрын
​@@7th_CAV_Trooper You don't need to use Visual Studio, it is simple to make plugins (better, update the existing ones that already support type hints) for most IDE's and code editors, you can even use something as neovim if you want to. And the question is not about read-only code, but the writting process, for your reasoning you also would never use the 'var' keyword or literally any of the new and implicit features of the language, so you are just blatanlty wrong.
@zbaktube
@zbaktube 6 ай бұрын
I always use the suffix. I can only add one more reason to @Palladin007's answer: async functions can be tricky because of the way it is implemented in c#. I just want to have it in my mind when I debug/fidget with them. I think this automatic type conversions, error handling, etc. related to async is not the best solution in c#. My opinion is that the c# compiler + jit could have decided on the run if a function is callable by async or not, and handle a function automatically accordingly. And, if somebody wants to change/force a behavior, add attributes to those functions. Microsoft could have hidden most of it from our view, but did not do that, stopped in half way. For me, async suffix keeps me concentrate on those half-way quirks when I saw them.
@jelle2819
@jelle2819 6 ай бұрын
Nowadays we have analyzers that help, in the past another reason was to spot issues where calls were not awaited. For me this last bit is still somewhat useful for code reviews and more quickly see in the intellisense what a method returns.
@clementdurazzo4774
@clementdurazzo4774 4 ай бұрын
It’s interesting to note that even if it’s not in the code base example, the framework remove the *Async suffixe pour generate a unique key to controller method signature (used in case of auto generating response url for Create for instance) and there is a configuration « to keep the Async suffixe in » in case needed.
@Yous0147
@Yous0147 6 ай бұрын
I do it the other way around. Like "Task KneadDough()" for async and and "Dough KneadDoughSync()" for synchronous. */s*
@discipuloschristi6787
@discipuloschristi6787 6 ай бұрын
100% agreed with Nick's approach on this one
@FXK23
@FXK23 6 ай бұрын
When a codebase has sync and async methods, it is confusing if the Async suffix is not present. That's because I've got used to this convention over the years and in a mixed sync/async codebase, the async suffix provides clarity. And to be honest, even if the whole codebase is an async-all-the-way exercise, there is always the opportunity to introduce sync methods, maybe to reduce state-machine overhead, maybe because some lib introduces sync and async methods or for any reason whatsoever. Naturally I will confirm to a given convention in projects, but I'll find it hard to loose my precious suffix. So for me it's rehab or try to stick with the suffix.
@edgeofsanitysevensix
@edgeofsanitysevensix 6 ай бұрын
Even though return a Task is very common now I still use Async convention, just because it hints at what is expected by the caller, I also use it internally on library code just so I know what it does.
@QuestionableOle
@QuestionableOle 6 ай бұрын
You put trust in that people would expect the async suffix as part of convention. For me personally the convention is only true / makes sense when there are overloads with both sync and async return types. Therefore in my personal code I will rarely use async suffix purely for the fact that my classes will for the most part be comprised of all async or all sync methods (helper methods excluded)
@alirezanet
@alirezanet 6 ай бұрын
For people like me who occasionally use a standard editor or VSCode, having an 'async' suffix is incredibly useful for identifying where the 'await' keyword is necessary. It's a common convention in nearly every codebase, and I tend to use it automatically. I don't always rely on analyzers, so this practice helps a lot.
@Marfig
@Marfig 6 ай бұрын
You don't need analyzers or fancy editors. Your compiler will throw warnings on every instance of an async method lacking an awaitable call and push them to the output window of your build.
@reikooters
@reikooters 6 ай бұрын
​@@Marfigyeah but then you deal with people who want to save 4 keystrokes that are also people who ignore compiler warnings
@megasuperlexa2
@megasuperlexa2 5 ай бұрын
so you do not know the signature of functions you are using. How do you pass the parameters?
@fadge316
@fadge316 6 ай бұрын
With regards to the controller names not having async. What about when you use nswag to auto generate a client? If you don't declare the name of the method in the Http verb, it'll give you some generic name. So, if you use the name of the controller method (nameof) - and you don't use the suffix pattern, then the implementer of the client won't know by method name that it's async. Any opinions on this?
@FrancoisNel256
@FrancoisNel256 6 ай бұрын
Clients will (should) always call a remote service with an async task, as the action to call it is an IO operation. So, regardless of whether the controller method has an Async suffex, the equivalent client call should have the suffex. And to my knowledge, for that, nswag always generates client methods with an Async suffex, regardless.
@DrGaurangGupta
@DrGaurangGupta 6 ай бұрын
I stopped using the suffix a few years ago. I used to when a sync was still new and there was mixed code with sync and a sync methods. 1. But now most code is async. 2. The return type is self-explanatory. For example ‘string’ for sync vs ‘Task’ for async. If you allow me a little exaggeration to make my point, this is just like you don’t need to suffix ‘string’ or ‘int’ to know what is being returned by a method.
@tobyjacobs1310
@tobyjacobs1310 6 ай бұрын
Very interesting. I was under the impression it was related to the risk of deadlocks with async targets (because of the captured context, risk of executing on the calling thread etc.) and the associated interplay with Task.Wait(). You need to be careful calling anything ending with Async; a method that returns a task and doesn't on the other hand...
@the-niker
@the-niker 6 ай бұрын
It depends. If the project is not a library I always assume an async-first approach. await LoadStuff(); LoadStuffSync(); Last 3 years I remember 2 instances where I used a Sync version of a method in a project (the cases were smells outside of my influence). Async is completely redundant in modern projects.
@danieleluppi6648
@danieleluppi6648 6 ай бұрын
I use it but not an easy pick.. of course you should add it if you provide both sync and async methods, but it's also very clear from the IDE when a method is async so it could be considered like a noisy word... and of course most important is the consistency along the whole project and guess we all agree on this.. in other words.. it depends.... 🙂
@MrEmub
@MrEmub 6 ай бұрын
I still use it, even though it's kinda expected still, it's very clear when using intellisense and browsing the mathods which are async, still helps people does really doesn't cause any harm.
@GiovanniCostagliola
@GiovanniCostagliola 6 ай бұрын
I use Async only when It’s the only way to solve an ambiguity. I think that “Async” should be treated as a kind of “overloading” and therefore should be transparent to the user for DX reason. Yes, DX over convention! This choice is particularly true when you use a functional library like Bogoware.Monads, for example, where both the Sync and Async functors have the same name. In this case writing functional code over Sync or Async is practically the same!
@Zullfix
@Zullfix 6 ай бұрын
How funny, I just had this conversation with someone a week ago. If I'm writing a contract, base class, or a public helper method, I'll use the Async suffix, but if I'm writing a private async methods inside a larger class, I probably won't use the suffix. This might be an artifact of not decoupling absolutely everything when possible according to SOLID, but I also think removing 15 LOC that is and will never be used elsewhere is redundant. Guidelines are great for keeping the public-facing API neat and tidy, but sometimes they require discretion before used in the niche private areas.
@ImmoLandwerth
@ImmoLandwerth 6 ай бұрын
We believe consistency trumps virtually any other consideration. The original reason why we have the async suffix is because we have sync versions. And even today we're often adding both sync and async versions for pragmatic reasons. The framework is extremely consistent here and you generally won't find methods that don't have the Async suffix. I'm biased but I consider not having the Async is as wrong as using camelCasing for members or not having an I prefix for interfaces. It works, but it's not idiomatic.
@creo_one
@creo_one 5 ай бұрын
- Not using "Async" suffix would be the same as not using "I" prefix for interfaces - We are using "I" prefix for interfaces, but not "A" prefix for abstract classes for some reason (if you wonder why prefix abstract classes - because they cannot be instantiated, which is IMO the main reason why we use "I" prefix) - I've seen commercial projects use Async suffix in action names (they even had linter to ensure that), no big deal - ASP doesn't give a damn about method name when attribute routing is used, so you are free to use whatever convention as long as Your coworkers understand it too - You are forced to abandon "Async" suffix in any case when method name is translated 1:1 to specific command/trigger/action in code, i was always under impression that this is the exact reason methods inside controller doesn't use "Async" suffix by convention.
@FusionBreakGames
@FusionBreakGames 6 ай бұрын
I get the point, but that would be just one more thing for me to remember all the time. Its much easier to always use an async suffix, especially since it does less damage than forgetting it.
@picu63
@picu63 6 ай бұрын
What is your opinion on using a suffix for methods that return an IAsyncEnumerable?
@user-xi1lm6vd5z
@user-xi1lm6vd5z 5 ай бұрын
Back in the late 80s we were thought to name our variables strName, intAge etc... conventions change. If I work in an existing library that uses Async suffix, I will continue to do so, even if there is no sync versions of those methods as it is more important to continue adding code in the same convention than the existing code. If I write a new library that only uses async methods and has no sync counterparts, I will not use that suffix. Having said that, I'm more than flexible and wouldn't loose time arguing over it in work as long as the code base of a library is using the same convention across the board.
@Mr8411s
@Mr8411s 6 ай бұрын
Back then I had a conversation on this topic with a colleague of mine. Basically, we decided to see it as a convention, which we just followed, however it would have made more sense, if there would have been async classes/interfaces/... instead of methods, so you would have a synchronous and an asynchronous variant of a class/interface/... . However, this probably would have meant a higher maintenance effort, so this may be just one of those things you just cannot do a "right way" 😅
@olegkap
@olegkap 6 ай бұрын
I also try to use Async suffix as convention but I would add another argument against using Async suffix in controllers, there is a bug from long time ago that if you want to use named route like CreatedAtAction then if method have Async suffix, route will not be found, you must strip Async suffix from method name to work
@qj0n
@qj0n 6 ай бұрын
I believe that if you really need to convey some language-level information by naming style then you lack some feature of editor. It's Hungarian notation again. If it's really important for a reader to see all async methods from the start, maybe set up IDE to mark the methods with something like cursive? Or maybe a warning every time you ignore return value (afaik, you already get a warning if you ignore returned Task in async method, but not in normal sync method) The sole fact that MS, as a primary provider of C# tooling, told everyone "Add 'Async' suffix to your methods or otherwise reader might miss that method is async" says that they didn't really think it through. Fortunately, their approach to developer experience improved much since then
@xdyps
@xdyps 6 ай бұрын
The edgecase herre is that C# allows for async void, and this would not be clearly visible for the developer due to the lack of return type Task and if the suffix was gone
@tanglesites
@tanglesites 6 ай бұрын
I think it does not matter, as long as your team is being consistent. However, I do like Nicks advice, it makes a lot of sense.
@Thorarin
@Thorarin 6 ай бұрын
I've kind of stopped using it in my (internal) application code several years ago. If I were writing a library - especially public - I would use the Async suffix. For an open source application project, I'd probably use it too.
@mkwpaul
@mkwpaul 6 ай бұрын
I generally are not a fan of rigid naming schemes or stuff like hungarian notation. Using Async suffix when there is an sync version and you need to have distinct names is fine. But otherwise it is redundant information. Just visual noise.
@b.h.5402
@b.h.5402 6 ай бұрын
I don't use async on personal projects. Instead, I change the verb from on any async methods from the infinitive (i.e. Create) to the present participle (Creating) as awaiting a present participle reads more obviously to me. var isCreated = await CreateAsync(customer); *vs* var isCreated = await Creating(customer); On projects with an actual team or one that will need to survive adding and removing developers as time goes on, I tend to stick with an -Async suffix.
@FleetingDream755
@FleetingDream755 6 ай бұрын
A more interesting discussion for me would if we need to have every thing as async when we really only ever await every statement as if it's synchronous anyway
@anotherinternetaddict
@anotherinternetaddict 6 ай бұрын
So much this
@ryankueter9488
@ryankueter9488 6 ай бұрын
The Async naming makes sense in circumstances where you are providing a library and you want to give the developer the option of making it synchronous or asynchronous. Typically, this functionality is used with longer running Tasks, which is what you want with a backend service so that any processing or exceptions don’t hang up the service. But for a small amount of code that is unlikely to throw an exception (e.g., because of missing resources), synchronous is actually better because async would add unnecessary processing overhead. This was common knowledge before the synchronous/asynchronous additions. But once again, this is another example of Microsoft giving junior developers plenty of rope to hang themselves.
@laszlo6501
@laszlo6501 6 ай бұрын
For controller actions you can tell aspnet core to suppress the async suffix ending.
@user-uk2qj7qk1x
@user-uk2qj7qk1x 5 ай бұрын
In new microservices we don't expect to use async and old synchronous methods, so we don't need to indicate that method is async. Either it returns Task/ValueTask or it has no any blocking operations
@vasiliychernov2123
@vasiliychernov2123 5 ай бұрын
Concurrency should be explicit to avoid pitfalls coming with it, so having Async suffix is better than not having it. I like how it's done in Kotlin, async methods (suspending functions) are sequential by default, so there's no need to add Async at all, because you can't forget to await them. They made concurrency opt-in by requiring you to wrap the method call into async {} block.
@recycledsoldier
@recycledsoldier 6 ай бұрын
If I'm writing a library that will be distributed, I tend to use Async to indicate intent to developers that may not be on our team. Internally within the same project, I tend to use Async only if there is a sync version of the same method and we need to indicate that one is async and one isn't.
@victor1882
@victor1882 6 ай бұрын
Yes, because of consistency, worse than a bad convention is an inconsistent one (but it's funny I'm saying that for C# of all languages)
@kRySt4LGaMeR
@kRySt4LGaMeR 6 ай бұрын
I don't use it because the codebase I work at is primarily async. But I do see the value on a sync-first project to differentiate.
@FantasyTeddy
@FantasyTeddy 6 ай бұрын
I use the Async suffix, because I like to enforce such guidelines with an analyzer (in this case Microsoft.VisualStudio.Threading.Analyzers).
@Grudzin7
@Grudzin7 6 ай бұрын
Adding 'Async' suffix is similar to adding [Pure] attribute whenever method does not affect state. You can do it and get used to doing it, but then if you forget it once it will make a lot of confusion later. For me it only makes sense to add Async suffix if there is another synchronous method in the scope. The same as I'd add some suffix if I got two identical methods returning different type. For any other case I'd skip Async suffix. Whatever you choose just remember to keep the whole solution in consistent style.
@KodingKuma
@KodingKuma 5 ай бұрын
Make sense!
@Carlos123-zk7qw
@Carlos123-zk7qw 5 ай бұрын
Being explicit for me at least is better. Same idea using for example "int" vs "var", I prefer to use "int". I know there are a lot IDEs out there where you can place you cursor on the method and you can see which type this var is , but I prefer to "save" that time .
@andrewcameron5852
@andrewcameron5852 6 ай бұрын
We don't use it at work for new stuff, because there's no sync version. If you try to call it without await, you'll get a squiggly line and a build warning which is far better than cluttering up the codebase. Using it these days without sync versions is like calling a property FirstNameProperty or calling a method CreateRecordMethod, it's completely redundant.
@burjisazrael4164
@burjisazrael4164 6 ай бұрын
I only use the Async postfix if there's an exact non-async version of the method with the same functionality. If I want to know if a method is asynchronous, all I need is to look at the return type.
@jameshancock
@jameshancock 6 ай бұрын
I’m mixed on this one. But the one I’m not is: don’t create interfaces without I prefix. Super annoying and you can’t tell if it’s implementing the interface or inheriting a class without looking in the thing.
@adriangodoy4610
@adriangodoy4610 6 ай бұрын
I'm the other way around you shouldn't care and the use of "I" tends to allow bad names in the code, IDatabaseRepository allows DatabaseRepository to exist without specifiying what this implementation is.
@jameshancock
@jameshancock 6 ай бұрын
@@adriangodoy4610 Absolutely not. It destroys discoverability because you can't know if you can just implement or if it has to inherit and completely changes design decisions because C# doesn't have multiple inheritance. Hence it has to be denoted otherwise you waste your life trying to figure it out before you design your system for no reason what-so-ever. Plus, all of the sane people do it, so when I find libraries like MassTransit that don't, it's super annoying because they're just violating all convention because they think they know better.
@adriangodoy4610
@adriangodoy4610 6 ай бұрын
if you are not in an IDE you have to open the sourcefile anyway to check the contract, if you are using an ide it just tells you with a simbol/ color@@jameshancock
@realsk1992
@realsk1992 6 ай бұрын
Maybe one solution would be if a keyword (oposite of "await", like "fire-and-forget") was required by the compiler if an asynchronous method is called without "await" and without assigning the result to a Task variable. So then a suffix would not be necessary.
@yurybatsyuro8293
@yurybatsyuro8293 6 ай бұрын
I tried to omit the Async suffix but came to a situation when I have a method that was void, became Task, but compiler didn't break and I didn't notice, and it lead to errors. So I returned back to Async because I want compilation to break and make me spray awaits.
@dire_prism
@dire_prism 6 ай бұрын
Async used to be this new weird beast, but it isn't any more and is often used by default. For legacy code it makes sense to continue using this naming convention for consistency.
@rostik18
@rostik18 6 ай бұрын
Somehow I also went to the same solution as you, Nick
@xeus
@xeus 6 ай бұрын
I was "taught" to use the "Async" suffix, but after looking into it myself, I don't do that anymore anywhere except in a case where (for some reason or another) both synchronous and asynchronous methods are required for the same thing.
@F1nalspace
@F1nalspace 6 ай бұрын
We use the async for every method that returns a task, its simple as that. Microsoft defined that convention many years before, so we sticked to it.
@Matt23488
@Matt23488 6 ай бұрын
I think it's important to challenge conventions like this. Analyzing the context of why it was a standard in the first place, and then seeing if the logic still applies today. I think it does not, and I might just stop using the suffix completely. It's the equivalent of some code that somebody deleted but left the comment, and for years people leave the comment in the code because they don't understand it (since the code it refers to is long gone). At some point you need to figure out if the comment actually applies to anything and delete it if it does not.
@Astral100
@Astral100 6 ай бұрын
Never used it myself either in my own code or shared code, because I never really had a reason to. I imagine if I write a public facing API of some kind I can see myself using it, or if I really need to have 2 versions of the same method, but so far I haven't really used it or needed to use at all. In fact I feel weird at the thought of adding async suffix to my methods.
@wobuntu
@wobuntu 4 ай бұрын
I'll stick to the suffix, even for Async-only APIs. Doesn't hurt and saves the caller who is probably not me a second to know what the thing is doing. Same for the Try* convention, immediately you know the return type is a Boolean and you'll have an out parameter with the result. This emerged and was established for a reason so I don't care if it just used by a framework only or by a human, in my opinion it should even be clear what the thing is doing when printing the signatures to a piece of paper without code and return types
Settling the Biggest Await Async Debate in .NET
14:47
Nick Chapsas
Рет қаралды 137 М.
How to make C++ run FASTER (with std::async)
23:10
The Cherno
Рет қаралды 252 М.
Зу-зу Күлпәш.Курс (6 бөлім)
40:48
ASTANATV Movie
Рет қаралды 481 М.
когда одна дома // EVA mash
00:51
EVA mash
Рет қаралды 11 МЛН
Stupid man 👨😂
00:20
Nadir Show
Рет қаралды 28 МЛН
UX designer Tries Udio AI Music Generator // App Review
11:51
Don’t Use the Wrong LINQ Methods
12:42
Nick Chapsas
Рет қаралды 45 М.
"Always Use Any over Count in LINQ" | Code Cop #008
9:56
Nick Chapsas
Рет қаралды 31 М.
Why Startups Hate .NET and C#
10:38
Nick Chapsas
Рет қаралды 238 М.
Async and await in C# example
11:56
kudvenkat
Рет қаралды 524 М.
Forget Grafana And Prometheus! Start With This.
10:51
Nick Chapsas
Рет қаралды 37 М.
"Stop Using Async Await in .NET to Save Threads" | Code Cop #018
14:05
Swagger is Going Away in .NET 9!
10:48
Nick Chapsas
Рет қаралды 45 М.
Зу-зу Күлпәш.Курс (6 бөлім)
40:48
ASTANATV Movie
Рет қаралды 481 М.