You're absolutely right. I tried doing it before but at the time it increase the font on things that I didn't want increased and it just looked odd. Will try to fix that. Thanks for the suggestion!
In first case it is terminated because still you are running in the main thread. Async Await is not by default running in sub threads / tasks. Here my async await video : ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-I4cnX_odC1M.html . continuewith is good if you are not awaiting the task result.
Agreed. I'd always wondered how to cancel the backend threads once the client canceled the request. Being able to pass the CancellationToken thru the endpoint answered that!
I actually intentionally left ConfigureAwait and .GetAwaiter().GetResult() because I will be covering them in a dedicated video, since it's just a big topic.
Something I did in a project when needing a resource loaded within a constructor was to build something that let me lazily load the data within an asynchronous context and await when I need it. It was just a small class built on top of Lazy that I called AsyncLazy. I can still pass in my interface that does the asynchronous call but stuff it inside of AsyncLazy and whenever I need that data I can just do (await _settingsLazy).; Plus, in my opinion, I like the way it reads. It tells whoever is reading that piece of code that the data is lazily loaded, cached after the first call, and is done within an asynchronous context.
async Task is dangerous if it's an event handler, basically the Task object will not be assigned and not GC-ed, thus catching exceptions will not work. async void is the way to go when used in event handlers or expect to not GC.
Actually in the async void is bad example it is not the Task.Run that causes the process not to die but changing the return type to Task and what that does to the method behind the scenes.
About the last case, when you need to resolve service from DI, there is an article at msdn 'Dependency injection guidelines' with anti-pattern examples where is shown how you can deadlock your thread with an async factory.
RE: "Don't sync over async in constructors" - do you have a clean solution for setting up this initialization pattern when using the Microsoft.Extensions.DependencyInjection namespace (IServiceCollection, AddScoped, AddTransient, etc.) for DI?
Making Task F() { using var g = G(); return H(g); } instead of async Task F() { using var g = G(); return await H(g); } is a straight way to get a disposed object accessed
In that specific case, the async/await must be used or pass a delegate to G() inside the task (or call the G() directly in the task). Always is better use the using keyword inside the task. I think the async/await overhead can become significant. However I return task if and only if certain 'rules' are met: * The method that returns the task has the same type of returned task or is a task without result. * The method that returns the task only executes that statement. * The method that returns the task executes that statement at the end and is the only asynchronous call one but, the parameters for this task must not be invalidable (collectable or disposable or mutable outside the task) in the lifetime of the method execution, that includes delegates or tasks (which should be awaited inside the returned task) as parameters. * The method that returns the task must uniquely choose from a finite set of tasks of the same type which one to do based on runtime conditions. Any violation to this 'rules' implicates use async/await.
As painful as it can be, I've definitely found situations where using the async keyword is not realistically possible. In a legacy application this can mean a huge change across a platform. Or for example a legacy 3rd party plugin that has some kind of hooks that don't support async for example But yeah... If you're writing a new code base just async all the things and thank yourself later
Hi Nick, thank you for your hard work and knowledge sharing here. It would be great if you elaborate about best practices on error handling. It is one on the wide and most useful topics. There are a lot of videos and resources on the internet, but still some of the ideas behind them are not clear for me. Thanks.
Another confusing topic you should have addressed is the .ConfigureAwait(Boolean) method on Task. Recent DotNetAnalyzers will prompt you to call this method on every awaited task by default. It's not always clear to people whether they can ignore that rule.
Well, for .NET Core you don't need to use it anymore, unless you're writing a library, because Core itself is not using SynchronizationContext anymore.
Disagree on ContinueWith. Where I have further processing on a Task, I find it convenient to be able to do that in a temporary scope so as to not introduce temporary variables into the outer scope (like you've done). Like chaining promises in javascript, it is very clean and simple. I don't see any convincing arguments here. To me, you've made the code worse by introducing a new variable (finalNumber). If you're going to say "Don't do something", you're going to need to say why.
There is one usecase where you can kind of not await everything... and that is technical debt. I was facing quite a few cases, where a call just had too many references to be refactored at once. For such cases I used the shown methods for getting the Task results. But I totally agree, in theory even that could be awaited. Its just a matter of priortity.
Hi Nick, can you explain to me, why should I write "return await new ValueTask(numberToAdd*2);", if I could also write "return numberToAdd*2;" directly. To explain more, we are in an asyc method, so return a value directly is automatically wrapped in a Task (or in this case a ValueTask). So what is the benefit of this additional await?
I don't see the benefit of async awayt outside UI at all. Most programers await all the calls even when not needed, where's the performance benefit of that? Nobody talks about how or why async await is better and where the performance gains come from. Actually as far as I seen on the industry maybe we have worst performance because async await
There actually many benefits (in my opinion more important than the UI use case) when using async await. It mainly has to do with IO operations that no longer have to lock your thread and wait synchronously for something like a database call to complete to move on. You can simply await the call and then that thread will go and do something else instead of wasting CPU clock cycles and when the database cal returns then the (or some) thread returns to continue the work. This allows your app to scale better because you can do more stuff with less resources.
@@nickchapsas I mean a problem on how people use it, as from the main to the end every async call has await on it. So the free thread only can wait for it. I've seen everybody using it but nobody taking advantage of that. The free thread can only wait because from main every call has await next to it
@@nickchapsas In fact I had pr's not approved for calling 3 non dependent async methods and awaiting them afterwards. And I had to make a demo project showing that that's exactly the use case for async methods
@@adriangodoy4610 that's how I understand the thing about async\await, if you have dependency on that async call, then do async and then await so you can do whatever you want with the data later on. Otherwise just use regualr function without the need of using that syntax
hi Nick, suppose i have a workflow with async method calls all the way to the repository, is it a good option to use "Task.FromResult" when i have one method which has no awaitable calls to force it async? or is it a better option to make the method simply syncronous?
20:46 How do you register a method in DI? I'm probably not searching about the topic properly cause I can't find information about that and I've never done it. Thank you for the video btw, I am really interested in improving my understanding of all the scenarios around async/await and love videos you make about that.
Yeah I forgot to mention that if you don't want that process to be cancellable then you shouldn't be passing the token. Something like an asynchronous email sending for example.
Nick Chapsas, in your first example, could you confirm whether awaiting would actually result in the application closing. As the task would pass back control to the main thread and just exit?
9:10 Well, no. If you're implementing a foreign Interface and that doesn't support async methods, and you need to await async methods inside sync methods of that Interface, there's no other way but to force synchronisation.
I have never used a .NET library in the past 5 years that either isn’t purely async or doesn’t over both a sync and async alternative for its implementation. I am happy to take a look at an example and offer an alternative though
I think the possibility of a deadlock is much more dangerous than wasting one more thread. Deadlocks are damn hard to spot and debug. Threads are hopefully quite cheap to create (and you can always revert them back if your performance really suffer from it)
The part at 5:53 is very confusing to me. Why is wrapping the code from SomeBackgroundThingAsync in a try-catch which re-throws, magically making Task.Run aware that an exception has been thrown ? When you say at 5:26 "there is a way to change this, so it throws an UnobservedTaskException", have you done this on the side without showing it between your run at 5:12 and 5:53 ? I tried in a sandbox to simply switch between try-catch and not try-catch, but the result is the same : Task.Run wil fire-and-forget.
Thank you for this video! Question: ist the cancellation token global for the whole application? Imagine having a windows service that just got the „shutdown“ command! Wo alle cancellation tokens fire?
I disagree with your async void is bad... any unhandled exception will crash your process, and you dont want something to crash without really knowing that it happened as you initially demonstrated. In that case you implement a try catch, which will still work the same way with async void as async Task.
Your video is good. But I want to add to the second point which is about `async void`. IMO it really depends on what you are doing and what is the limitation. More specifically, if you are working with APIs that are not thread-safe, and thus you can't use `Task.Run`, then using `async void` is fine, since `await async` without using `Task.Run` runs in the main thread (which is why the exception in the example crashed the whole process). I guess this happens more likely when working with game engines whose APIs are most likely not thread-safe.
@@nickchapsasI had written a game for Xbox live indie games back in 2010 before async/await with c# and xna, and that was probably around the time I also stopped working professionally with c#. After about 10 years I wanted to get back into .net and c# and thought I should port my game to monogame, and uwp to make it work on both windows and newer Xboxes. That's where I had to figure out this new to me async/await. I struggled the most with this one aspect, everyone telling me to avoid async void, and not knowing a better way to integrate async apis into a framework that doesn't support it, specifically update/draw functions from the monogame/xna. Anyways, it would be great if you made a video about that kind of real world integration issue. In any case, I enjoy your content and your knowledge. Keep up the good work.
@Nick Chapsas Await is pausing the current process until the resolution of the awaited task. This is not only a question of state machine allocation. By immediately awaiting every tasks you're making your code work synchronously. Consider this code : Var taskOne = doStuffAsync(); Var taskTwo = doOtherStuffAsync(); Await taskOne; Await taskTwo; Doing like this task one and task two are being executed simultaneously. If you're immediately await the functions you are in fact executing them one after an other, aka synchronously.
I’m wondering why it's should be preferred since await should be called where result(or exception) is needed. I don’t use async/await for arrow(wrapper) function which is only prepares input parameters. And also use ContinueWith when need to re-cast result without awaiting public Task GiveMeInt() => Task.FromResult(1L).ContinueWith(task => (int)task.Result, TaskContinuationOptions.ExecuteSynchronously); Await is very optimized in core, but it’s much heavier in full framework.
Thanks for video. I have a question about a scenario I need to code. I have a process that will send a request file via SFTP and then I will need to wait for a response file to be created on the ftp server before I download and continue my processing. The response file could appear within 1min to 60mins. If I await this process, is there a way that I can say, give up after 60 mins?
In VB6 we were told not to use DoEvents because it was bad practice. Now we are told to do it in an even more complicated way in C#/VB.NET, using await and async, a way that doesnt solve any of the reasons we were told not to use DoEvents back then and also has a more limited utility (its all or nothing with async, doevents is any time you want) In VB6 we were also told not to use OnError because it was bad practice. Now we are told to use exceptions, something less capable than OnError (see the distinction between Resume and Resume Next.) Spaghetti in the form of objects is still spaghetti.
Love the information shared ! Thank you Nick. Learned a lot from the "Always pass the CancellationToken" and the "Don't sync over async in constructors" !
The problem I see with the last example, is that static methods are a pain to mock in unit tests. Injecting ConnectionFactory and then using it in specific methods to get MyConnection is probably a better approach? Unless the Connection has to be shared between methods, but it'd mean we need atomicity. Does it make sense to have multiple methods in such case?
... is supported starting with C# 7.0, good tutorial. A good video tutorial will be about your words: " in the dot net scenario there is no way that you cannot await a call ".Thank's for sharing ...
Nick, can you please explain this to me. @ the 11:19 mark, you are awaiting the number from an async call. Won't the next line of code run and fail if the await call takes a while?
Realy like ur videos about .net. Are you going make video about delegates in c#? More about their usage, cause theory is quiet simple, but there very few good examples of their usage.
Is it really true that SomeBackgroundThingAsync() is actually a background thing? I'd say it's synchronous until it hits an await and then it depends on the current sync context or task scheduler where the continuation carries on.
@@patrikbak8161 in the case of task.run it is registered in and running on the task pool. But with the void the code gets executed immediately up to an await, but after that... I know it will return to the controller and continue the controllers' path. But that function... It probably gets cleaned up by the GC. It would be the same as if you created a task 'dostuff' in a non async function. And in 'dostuff' yielded immediately. Unless you do something with the returned task, 'dostuff' will never continue it's code path beyond the yield.
Awesome tutorial Nick. One example of something you cannot make async (I haven't been able to). Is event calls on WinForms and WPF. Take the following Load event on a Form or WPF Window. public async void Load() I can do however if I try public async Task Load() it won't compile. Interested to know your work around to make these async. Custom events I can do, as I declare the delegate, but built in ones are tricky.
How do you solve an await in a get; set; private string MyCarResult; private string MyCar { get { return MyCarResults; } set { MyCarResults = value; await someFunction(MyCarResults); } }
You turn MyCar into a field and you create proper async setter. Your setter should just set the value and not really do any other stuff unless it's a domain model in which case just move it to a separate method and then set the field value.
The cancellation token should be used with care. Canceling a save operaton half-way through could leave your database in a undesirable state (half-saved objects).
Ideally all your db operations in a since call should be atomic. Breaking them down to multiple calls or having them be non-transactional is dangerous no matter whether you use a cancellation token or not
Great Video, Short question do you know if they fixed the problem where cancelation tokens don't trigger in IIS? Cause it still a problem for me at least with the Controllers token in the API Thanks
Hmmm I was taught, by MS that you should not always await every method that returns a task because that's a ton of overhead. If you are not doing something with the task return value there is no need to await. This creates state machines which adds not only CPU cycles but also the memory your app uses. Please explain why you think every task method should be awaited. Thanks!
I may add, that RUN TASK, thing, It is to wrap an otherwise NOT await-able method, for UWP and Windows Sdk App. (WPF programmer, don't know UWP, will be confused.) Example, Windows Sdk App, in side a converter -> will crash, if you copy a WPF converter and try to use on "IT": you need to do this: try { Task.Run(async () => { var stream = await file.OpenReadAsync(); dispatcher.TryEnqueue(async () => await BI.SetSourceAsync(stream)); }); return BI; } ___________ in other words: If you have a BIG method coded with WPF, do not want to recode it for UWP/WAP, That, run-task thing, is very useful. Another Example, with WPF, fetch SQL return from local database, it will wait and blocked, unit it is COMPLETED. Copy that block of code to UWP, it may not work, or crash. Because? the method will return immediately, before the result is completed. FIX? -> that run-task await thing.
Here's mistake #9 (or #1 imho). Avoid introducing async/await into a legacy codebase that does not use it, unless you're working with a team of async/await experts. Even then I'd say it's not advisable.