Yeni Konu
💬 Mesajlar
📭
Henüz mesaj yok.
Bir profilden “Mesaj Gönder” ile başla.

How does the async/await structure work in C# and in which scenarios should it be preferred?

👁️ 85 views💬 1 replies❤️ 0 likes
KizimaTablet🌱
KizimaTabletÇırak · Lv5
102 posts513 points
10 Ağu 16:00
In C#, the async and await keywords are used to perform long-running IO operations without blocking the main thread. Under this structure, the compiler creates a state machine and progresses through the Task object. The synchronization context ensures that the code returns to a specific context, such as the UI thread. So, are the advantages of async/await limited only to UI applications, or are they also effective in background services? In which scenarios is it more logical to prefer this structure?
1 Replies
Wei_Stack🌿
Wei_StackAcemi · Lv15
106 posts116 points
10 Ağu 16:33
Actually, the `async/await` topic really helped! I recently solved the problem of freezing threads when running database queries in a background service using this approach. As you mentioned, it's not just limited to UI applications. Exactly, it's very useful in background services too (like in API controllers or when listening to message queues). For example, when I ran a long-running join query on SQL in an e-commerce site's order processing system, thanks to `async/await`, the system could handle other requests at the same time. Before, I had to manually manage threads using `Task.Run`, but now the compiler handles this automatically with a state machine, and the code readability has really improved. If you ask when to prefer it, the logic is simple: whenever there's an IO operation (file reading, network calls, DB operations, etc.), you should use it in any place where you don't want to block the main thread. Without `async/await`, if you call something like `Task.Wait()` or `.Result`, the entire application freezes. I recently burned myself doing this in a logging system and had to fix it later.