How to use Async/Await/Task in C#

  Рет қаралды 77,191

Raw Coding

Raw Coding

Күн бұрын

Пікірлер: 120
@alejmc
@alejmc 3 жыл бұрын
Wow, it has come such a long way. I remember about 10+ years ago, don’t really know how early WPF was at the time, was trying to understand MVVM patterns, XAML as the view, etc and the whole thing had a ‘Dispatcher’, ‘Context’, etc for jobs , to force the results to be piped to the main UI thread (if I remember right). Now by default it joins the UI thread... and code is written quite linearly. This is magic. Thanks for the dedication in sharing this.
@RawCoding
@RawCoding 3 жыл бұрын
Thank you for watching and sharing some history :)
@ziyuxie8112
@ziyuxie8112 4 жыл бұрын
you're the man! thanks for your dedication
@RawCoding
@RawCoding 4 жыл бұрын
Thank you))
@Kihera-zd8re
@Kihera-zd8re Ай бұрын
i like that you repeat yourself and is thorough because this is complex (for me). :)
@myme1474
@myme1474 Жыл бұрын
Very helpful follow up video for some solid DO's and DON'Ts fundamentals.
@AllAboutDataTechnology
@AllAboutDataTechnology 11 ай бұрын
good and simple example of using these topics. thanks for the video!
@dmytrokulak
@dmytrokulak 4 жыл бұрын
Awesome delivery of the content: clear and engaging. 👍
@RawCoding
@RawCoding 4 жыл бұрын
Cheers)
@ohaRega
@ohaRega 4 жыл бұрын
Awesome. Subscribed. Helped me a ton.
@RawCoding
@RawCoding 4 жыл бұрын
Awesome!
@gopikrishnag41
@gopikrishnag41 4 жыл бұрын
I learned fundamental more clearly.. great video. Thanks for your great dedications :)
@RawCoding
@RawCoding 4 жыл бұрын
Thank you :)
@selmangulmez6476
@selmangulmez6476 Жыл бұрын
You make my day man.
@joao-gf4qt
@joao-gf4qt 25 күн бұрын
Amazing video!
@haha-hk9tx
@haha-hk9tx Жыл бұрын
Ur channel is a gold mine :D
@angmak7321
@angmak7321 Жыл бұрын
You really made my day.
@TheMichaelRUS
@TheMichaelRUS 4 жыл бұрын
Спасибо за видео!)
@RawCoding
@RawCoding 4 жыл бұрын
Спасибо что посмотрел )
@taraspelenio8259
@taraspelenio8259 4 жыл бұрын
@@RawCoding Do you speak Russian as well?
@RawCoding
@RawCoding 4 жыл бұрын
Yes
@kolesplace
@kolesplace 3 жыл бұрын
Very well explained. Thanks!
@RawCoding
@RawCoding 3 жыл бұрын
Thank you
@smitank2895
@smitank2895 3 жыл бұрын
👍 very nicely explained
@RawCoding
@RawCoding 3 жыл бұрын
Thank you
@kamilmikua5794
@kamilmikua5794 Жыл бұрын
Thanks for video, that helps a lot!
@rotacioskapa4251
@rotacioskapa4251 2 жыл бұрын
would be cool to see why should we avoid those that you marked or said BAD/Dont do this, some explanation on what could go wrong with those
@RawCoding
@RawCoding 2 жыл бұрын
Cool
@manishmoon8
@manishmoon8 4 жыл бұрын
I believe if we don't use ConfigureAwait or use ConfigureAwait(true), then after returning from await it does not execute on calling thread, it's just calling thread context is stored, and when network driver hands the result to one of the threadpool thread.. the saved context of the calling thread is copied into this threadpool thread (meaning the code after await still execute of the threadpool thread not on the calling thread). It's applicable for Dotnet framework not asp.net core since core do not have any SynchronizationContext .
@RawCoding
@RawCoding 4 жыл бұрын
Sounds reasonable
@dimarogov8445
@dimarogov8445 2 жыл бұрын
Thanks for explanation!
@MarinaMarina-fr8ex
@MarinaMarina-fr8ex Жыл бұрын
Great video!
@expertreviews1112
@expertreviews1112 3 жыл бұрын
Love your content! More power to you
@RawCoding
@RawCoding 3 жыл бұрын
Thank you
@taraspelenio8259
@taraspelenio8259 4 жыл бұрын
Again, very good video, It was interesting and informative to watch the video. Could you please share some link with description, why we should avoid using of 'async' and 'Task' together in one method?
@RawCoding
@RawCoding 4 жыл бұрын
In my previous video I show you that async creates a state machine, you want to avoid making a state machine but not sacrifice readability.
@aamirali6914
@aamirali6914 2 ай бұрын
i am bit confused is async spawn state machine(3:03) or Task(3:48) you told its async somewhere you told its Task so if i want to avoid state machine which one i shouldnt use async or task
@RawCoding
@RawCoding 2 ай бұрын
Task is just a class that marks something to be asynchronous, so tasks can be awaited. async creates state machine
@aamirali6914
@aamirali6914 2 ай бұрын
@@RawCoding Thanks for the guidance.
@my2centsobservations
@my2centsobservations Жыл бұрын
Hi there, how does the runtime decides that the thread it frees while processing a long asynchronous task, will not be assigned to a synchronous task? Or can it be assigned to any request/task regardless of asynchronous or not?
@RawCoding
@RawCoding Жыл бұрын
It's a bit incorrect to think that you put tasks on threads, it's more like there is a pile of tasks (objects) and threads eat (process) from that pile. 1. eat task 2. reach await and stop eating 3. wait for interrupt from IO hardware component to reach runtime and then runtime instructs the thread pool to assign a thread to eating the task again the "eating" motion is re-entering the task (state machine object), if the task contains a blocking operation (lock) the thread pool will be stuck trying to eat the task. A thread cannot eat 2 tasks at the same time. It can be told to eat 1 task and then once it completed a step in the state machine it can be told to eat another task. Hope this helps
@TechofthedayByNK
@TechofthedayByNK 4 жыл бұрын
Nice content. I kind liked the idea to help fellow techies by creating videos. And that's why i also started doing Azure videos.
@RawCoding
@RawCoding 4 жыл бұрын
Awesome, wishing you luck :)
@TechofthedayByNK
@TechofthedayByNK 4 жыл бұрын
@@RawCoding Thanks!
@rick5522
@rick5522 Жыл бұрын
Thanks for this awesome explanation! I have one question. A process has thread(s) and within a process thread(s) share memory. Then why do we need a certain thread for UI?
@RawCoding
@RawCoding Жыл бұрын
The problem with the ui thread is something you don’t see you need something to say draw pixels on screen, having multiple threads write to screen is not a thing kind of like writing to the same file in parallel.
@rick5522
@rick5522 Жыл бұрын
@@RawCoding Fair-enough :) Thank you!
@rick5522
@rick5522 Жыл бұрын
@@RawCoding In web development, I think I found our UI thread. So in a Blazor Server app, I have a component: Counter: @Counter Start Timer @code { public int Counter { get; set; } private void StartTimer() { Timer timer = new Timer(TimeCallBack, null, 1000, 1000); } private void TimeCallBack(object state){ if(Counter < 5) { Counter++; Console.WriteLine("Counter " + Counter); // Use InvokeAsync to switch back to the UI thread before triggering UI update InvokeAsync(() => StateHasChanged()); // TimeCallBack method executed by another thread? // StateHasChanged(); } } } First I used StateHasChanged(); Simply, I wanted to re-render my component but I got this error: The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state. It seems like a perfect example of UI thread importance. Can you confirm my assumption?
@kev797
@kev797 2 жыл бұрын
could you explain the use of lock() ?
@RawCoding
@RawCoding 2 жыл бұрын
you reserve a scope of code to only be executed by 1 process at a time.
@helium73
@helium73 4 жыл бұрын
I"m trying to learn sockets and I'm new to C# and am overwhelmed with all the different libraries you can use and all the ways to do it. Each example is pretty much incompatible with every other example. I came across one that used await and it's the only one that shows how a server can message a webpage. Anyway I can't get that example to receive a message. All I get is numbers. It seems that the best method for chat might be callbacks. So that's another situation where the same thing can be done in many ways. Callbacks vs async await. You would think that the machine could handle just waiting for a response in some cases just for development speed. Anyway I'm thinking the best way to explain things is to explain all the different ways to handle asynchronous programming. Another one is threads. I watched your other video and you brought in threads really quickly so I guess async must create a thread behind the scenes.
@RawCoding
@RawCoding 4 жыл бұрын
the async programming model is meant to be an abstraction on top of the threads/processors, and I bring them in because we were going under the hood. The reality is you don't need to be concerned with much of that stuff, because all you are doing is you are saying some external thing is going to do some work and you don't want your application to hang. For chat app I'd reccomend looking in to signalR it's pretty good :)
@keyable
@keyable Жыл бұрын
If I use Task as output in Method (without async/await) will it work asynchronous anyways? thnx!
@RawCoding
@RawCoding Жыл бұрын
Yes
@mrt7948
@mrt7948 2 жыл бұрын
this is good. thanss
@RawCoding
@RawCoding 2 жыл бұрын
Cheers
@pmro
@pmro Жыл бұрын
Hi, thx for your videos. I have a question related to "do not use async in a constructor" - Why?
@pmro
@pmro Жыл бұрын
I've found answer for my question here -> kzbin.info/www/bejne/gGHQlIyMra94opI :)
@amitsharma-yu1ju
@amitsharma-yu1ju 2 жыл бұрын
When does async and Task fit in event driven systems
@RawCoding
@RawCoding 2 жыл бұрын
At IO level
@HEbr-rg2jz
@HEbr-rg2jz 4 жыл бұрын
Let's say I have a method like this in a repository(It's not very correct): Task Insert(T something) => _ctx.Add(something); But as I'm gonna use this in a wpf app I need to add ConfigureAwait(false), now the Add method returns a ConfiguredTaskAwaitable. and I cannot return Task directly. It compiles this way: async Task Insert(T something) => await _ctx.Add(something).ConfigureAwait(false); Is there a way to avoid creating state machine in this method?
@RawCoding
@RawCoding 4 жыл бұрын
The caller of the task would have to configureAwait false. Make a distinction between creating a task (which is what we do if we don’t await it) and executing the task which is when we await it.
@HEbr-rg2jz
@HEbr-rg2jz 4 жыл бұрын
@@RawCoding Thanks for replying, but looks like I can't avoid nested asyncs in here.
@sagivalia5041
@sagivalia5041 Жыл бұрын
So, if you wanna do smth with the contents of a task, you have to retrieve with async/await and if you just pass the task around you can omit the async/await?
@RawCoding
@RawCoding Жыл бұрын
Yes
@sagivalia5041
@sagivalia5041 Жыл бұрын
@@RawCoding I see, so a main controller method of a web api with db queries and/or email sending is likely to be async? (as an example), since we `await` to get the results of the query?
@RawCoding
@RawCoding Жыл бұрын
Yes
@sagivalia5041
@sagivalia5041 Жыл бұрын
@@RawCoding Thank you
@abuzeromohammed3386
@abuzeromohammed3386 4 жыл бұрын
is there more resources that make this more clear ,it still seems confusing to me ?
@RawCoding
@RawCoding 4 жыл бұрын
What are you confused about?
@erokazen
@erokazen 3 жыл бұрын
What extensions do u use to make VS symbols look pretty !?
@RawCoding
@RawCoding 3 жыл бұрын
JetBrains mono font
@erokazen
@erokazen 3 жыл бұрын
Thanks a lot 👊🏽
@stevenotlisted2129
@stevenotlisted2129 4 жыл бұрын
I enjoy your videos and am watching more. I need to start a side ASYNC process that checks the internet API every 30 seconds and then updates a flag so I can set an icon to green, Been struggling with the ASYNC and wanted to know if you hve done this before and can offer some coaching?
@RawCoding
@RawCoding 4 жыл бұрын
Come ask your question on discord with code examples
@stevenotlisted2129
@stevenotlisted2129 4 жыл бұрын
@@RawCoding I am new to the youtube channel stuff. What is discord?
@RawCoding
@RawCoding 4 жыл бұрын
It’s like a server with chats n stuff for discussion, link is in the description of the video
@andreh1200
@andreh1200 4 жыл бұрын
What keyboard are you using?
@RawCoding
@RawCoding 4 жыл бұрын
Flico Convertible 2 Tenkeyless MX brown, just to warn you the wireless Bluetooth isn’t perfect
@andreh1200
@andreh1200 4 жыл бұрын
@@RawCoding That's fine, thanks!
@bendittachacko
@bendittachacko 2 жыл бұрын
how to resolve cannot convert "void" to "system.threading.tasks.task" ??
@RawCoding
@RawCoding 2 жыл бұрын
public void Fn(){ } //
@hermandsen
@hermandsen 4 жыл бұрын
Thank you for another great video. Question: On a web-app, should I await my task inside the view, or should I await the task in the controller, and then populate my view-model with the data? Should a view-model contain tasks?
@RawCoding
@RawCoding 4 жыл бұрын
The View can contain and execute tasks with await, that's not a problem. But you want to create the model outside the view.
@levanhuynh39
@levanhuynh39 4 жыл бұрын
@@RawCoding Thank you for another great video. as you said, "The View can contain and execute tasks with await" so what if I use postman or jquery to send request ? Could it handle task or not ?
@RawCoding
@RawCoding 4 жыл бұрын
What? Task is a c# construct
@fiyora
@fiyora 4 жыл бұрын
What's the difference of just calling Notify() (without await) and Task.Run(() => Notify()) ?
@RawCoding
@RawCoding 4 жыл бұрын
It’s fire and forget, you never get the result back.
@TakuCoding
@TakuCoding 4 жыл бұрын
I have been doing some flutter tutorials, they are nice and all but there is no one explaining how I can link up an Api in core and flutter to do a crud is it possible for you to do a crud Api with flutter and .net core tutorial
@RawCoding
@RawCoding 4 жыл бұрын
Join for my Sunday streams, I’m currently hooking up a flutter app to identity server and going to be calling the api next, stream will be uploaded on Wednesday.
@TakuCoding
@TakuCoding 4 жыл бұрын
@@RawCoding can't wait
@turqayu3548
@turqayu3548 4 жыл бұрын
Great content,can you make some tutorials for SignalR?
@RawCoding
@RawCoding 4 жыл бұрын
I have one it’s not great.
@turqayu3548
@turqayu3548 4 жыл бұрын
Raw Coding hmm maybe create a playlist because i can’t find much high quality tutorials on it
@RawCoding
@RawCoding 4 жыл бұрын
In the future, SignalR isn’t complicated you shouldn’t have a problems implementing it.
@Vesparion
@Vesparion 4 жыл бұрын
You say "still remain with non task main" should we always aim to have non async/task main?
@RawCoding
@RawCoding 4 жыл бұрын
It doesn't really matter that much :)
@nithinchandran7959
@nithinchandran7959 4 жыл бұрын
What happens if we do not await an awaitable?
@RawCoding
@RawCoding 4 жыл бұрын
You’ll never consume the result, and if you have closures they might get disposed of and crash the task
@nithinchandran7959
@nithinchandran7959 4 жыл бұрын
@@RawCoding but in your tutorial, you use Task. Run method like a fire and forget process. It Itslef returns a task object and we aren't awaitimg it anywhere. Whats the difference?
@RawCoding
@RawCoding 4 жыл бұрын
If the task is isolated it just runs in the background
@sanphir
@sanphir 2 жыл бұрын
I still can't figure out how I should avoid using state machine. In most of you examples you are using async which means using state machine. Can someone clarify this for me?
@RawCoding
@RawCoding 2 жыл бұрын
Task do() => someTask; async Task do() => await someTask; First example we just return the task - no need to await or use async no state machine. Second you are awaiting the task and having to use async for that - generates state machine. You want to avoid 2 when it’s obvious. Otherwise you don’t have to worry about not creating a state machine.
@sanphir
@sanphir 2 жыл бұрын
@@RawCoding Thank you!
@clearlyunwell
@clearlyunwell 3 жыл бұрын
👍🏽
@RawCoding
@RawCoding 3 жыл бұрын
)
@thedanielspindler
@thedanielspindler 8 ай бұрын
Also watch Writing async/await from scratch in C# with Stephen Toub --> kzbin.info/www/bejne/iF7dY3usYpyhrs0
@caunt.official
@caunt.official 4 жыл бұрын
А зачем ты рекомендуешь не использовать .GetResult(), и в первой строчке входной точки программы используешь его?) Имхо лучше показать людям как правильно, даже учитывая что компилятор все равно превратит это в .GetResult()
@RawCoding
@RawCoding 4 жыл бұрын
Прости немножко не понял, что привносится в GetResult()?
@caunt.official
@caunt.official 4 жыл бұрын
@@RawCoding возможно я не понял вопрос) но .GetResult() ведь блокирует поток и ожидает результата, а людям нужно объяснить что б использовали async/await во избежание этого) Видео уже довольно старое, возможно мой комментарий неуместен и вы уже используете асинхронность во входной точке программы)
@RawCoding
@RawCoding 4 жыл бұрын
GetResult() блокирует и поэтому я не рекомендую его использовать; те кто понимают где это не составит проблем могут блокировать, я например пользуюсь этим в стартапе своей программы перед тем как она запускается
@michaelgavila
@michaelgavila 3 жыл бұрын
Please don't create new HttpClient for every request people. HttpClient is intended to be instantiated once and reused throughout the life of an application.
@RawCoding
@RawCoding 3 жыл бұрын
Tbh HttpClient is not the problem the handler is. But good advice to follow for newbies
@rmcgraw7943
@rmcgraw7943 22 күн бұрын
.NET pools HttpClient now; even connections are pooled.
@janinesmith1662
@janinesmith1662 2 жыл бұрын
public async Task M1() { await Task.Delay(1000); Console.Write("M1"); } public Task M2() { Console.WriteLine("M2"); return Task.CompletedTask; } ------then calling---- public async Task End1() { await M1(); await M2(); } public async Task End2() { var t1 = M1(); var t2 = M2(); await t1; await t2; } End1() call (=> M1M2) and End2() call (=> M2M1) have different results. I dont understand why..could you explain please ? Thank you:)
@RawCoding
@RawCoding 2 жыл бұрын
End1 you await each task sequentially, end2 you kick off the 2nd task without waiting for the 1st to finish which has the delay
@faridmammadzada
@faridmammadzada Жыл бұрын
Hey, great tutorial, thanks a lot, and i would like to recommend this video for you , because it mentions the benefits of using async/await kzbin.info/www/bejne/l5KmYml8q5etm9U
@poeticjystice
@poeticjystice 4 жыл бұрын
do you have money?
@RawCoding
@RawCoding 4 жыл бұрын
Yes
Semaphore Explained C#
12:24
Raw Coding
Рет қаралды 41 М.
What are ASYNC and AWAIT in C#? Asynchronous Programming Tutorial
18:34
Noodles Eating Challenge, So Magical! So Much Fun#Funnyfamily #Partygames #Funny
00:33
Quando A Diferença De Altura É Muito Grande 😲😂
00:12
Mari Maria
Рет қаралды 18 МЛН
Lamborghini vs Smoke 😱
00:38
Topper Guild
Рет қаралды 53 МЛН
C# Async/Await/Task Explained (Deep Dive)
24:22
Raw Coding
Рет қаралды 418 М.
Settling the Biggest Await Async Debate in .NET
14:47
Nick Chapsas
Рет қаралды 147 М.
C# Async Programming - Part 1: Conceptual Background
29:49
Rainer Stropek
Рет қаралды 66 М.
"Stop Using Async Await in .NET to Save Threads" | Code Cop #018
14:05
C# Multithreading - Master Threads and Tasks
9:51
tutorialsEU - C#
Рет қаралды 37 М.
8 await async mistakes that you SHOULD avoid in .NET
21:13
Nick Chapsas
Рет қаралды 315 М.
C# Async Await Mistakes | Part 1
10:19
Amichai Mantinband
Рет қаралды 37 М.
C# Channels Explained (System.Threading.Channels)
47:11
Raw Coding
Рет қаралды 37 М.
Noodles Eating Challenge, So Magical! So Much Fun#Funnyfamily #Partygames #Funny
00:33