The choice of Task.run and Async-Await in WPF applications: architecture considerations
In WPF applications, choose to use Task.run or async-Await, especially when there is a stall in UI, it is a common problem. In order to solve this problem, the following factors need to be considered:
<.> 1. UI thread block:
Async-Await is not carried out on the background thread. If the waiting operation is a CPU -intensive task, it may cause UI stuck. To prevent this, use TASK.RUN to entrust such tasks to the background thread.
<.> 2. Thread efficiency optimization:
Use task.run to package the outermost asynchronous call to reduce the thread overhead of the .NET. This ensures that all subsequent Async-Await operations in the call will be performed on the background thread. <.> 3. Code and CPU dense method:
Avoid using task.run in reusable code. Instead, use TASK.RUN to call the CPU -intensive method, and to clearly explain its CPU -intensive characteristics in the method signature. This separation allows to be flexibly reused components without affecting the efficiency of the background thread.
UI thread optimization Best practice:
In addition to using task.run carefully, follow the following criteria to maintain the rapid UI thread:
Keep the UI thread operation within 50 milliseconds to avoid blocking.
Limit the continuation of the UI thread at about 100 times per second.Use configureawait (false) to optimize the performance when restoring AWAIT operations on the UI thread.
The above is the detailed content of Task.Run vs. Async-Await in WPF: When Should I Use Which for Optimal UI Performance?. For more information, please follow other related articles on the PHP Chinese website!