This line will yield control to the UI while CalculateDamageDone() Does an expensive calculation and returnsĬalculateButton.Clicked += async (o, e) => private DamageResult CalculateDamageDone() This allows the UI to feel smooth as the work is being done. The best way to handle this is to start a background thread, which does the work using Task.Run, and await its result using await. Performing the damage calculation can be expensive, and doing it on the UI thread would make the game appear to pause as the calculation is performed! Say you're writing a mobile game where pressing a button can inflict damage on many enemies on the screen. CPU-bound example: Perform a calculation for a game The code expresses the intent (downloading data asynchronously) without getting bogged down in interacting with Task objects. Var stringData = await _httpClient.GetStringAsync(URL) The UI thread is now free to perform other work. This line will yield control to the UI as the request It can be accomplished like this, using the class: private readonly HttpClient _httpClient = new HttpClient() ĭownloadButton.Clicked += async (o, e) => You may need to download some data from a web service when a button is pressed but don't want to block the UI thread. I/O-bound example: Download data from a web service While there are ways to approach async code other than async and await, this article focuses on the language-level constructs. It yields control to the caller of the method that performed await, and it ultimately allows a UI to be responsive or a service to be elastic. The await keyword is where the magic happens. For CPU-bound code, you await an operation that is started on a background thread with the Task.Run method.For I/O-bound code, you await an operation that returns a Task or Task inside of an async method.The model is fairly simple in most cases: ![]() They are supported by the async and await keywords. The core of async programming is the Task and Task objects, which model asynchronous operations. ![]() It follows what is known as the Task-based Asynchronous Pattern (TAP). You could also have CPU-bound code, such as performing an expensive calculation, which is also a good scenario for writing async code.Ĭ# has a language-level asynchronous programming model, which allows for easily writing asynchronous code without having to juggle callbacks or conform to a library that supports asynchrony. If you have any I/O-bound needs (such as requesting data from a network, accessing a database, or reading and writing to a file system), you'll want to utilize asynchronous programming.
0 Comments
Leave a Reply. |