use*_*346 2 asp.net-mvc async-await
说我有
public class MyController : Controller
{
...
public async Task<IActionResult> MyAction()
{
DoSomethingSync();
return View();
}
Run Code Online (Sandbox Code Playgroud)
用得好吗?难道它不应该至少有一些异步来证明“异步任务 L...”定义的合理性吗?该控制器中的每个操作似乎都遵循相同的模式。
编译器向您发出警告是有原因的。不要忽视它。如果您的方法不需要是async,那么请勿将其标记为这样。只要您只需async在方法签名中包含该单词,编译器就会生成一堆代码来支持异步。这些额外的代码将无缘无故地运行,从而降低性能。
作为一个例子来向您展示它是多么浪费,我运行了一个非常基本的基准测试,比较了两种方法BenchmarkDotNet:
[Benchmark]
public static async Task<string> AsyncString()
{
return "This is my string This is my string This is my string This is my string This is my string";
}
[Benchmark(Baseline = true)]
public static string String()
{
return "This is my string This is my string This is my string This is my string This is my string";
}
Run Code Online (Sandbox Code Playgroud)
结果:
| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------ |-----------:|----------:|----------:|------:|--------:|-------:|------:|------:|----------:|
| String | 0.0000 ns | 0.0000 ns | 0.0000 ns | ? | ? | - | - | - | - |
| AsyncString | 27.2304 ns | 0.7644 ns | 2.1685 ns | ? | ? | 0.0172 | - | - | 72 B |
Run Code Online (Sandbox Code Playgroud)
仅仅使用async就会导致 72 字节的分配,这会给 GC 带来压力,并且比替代方案慢得多。最重要的是不要忽略编译器警告。
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |