影响时 - 等待没有任何等待调用的异步方法

时间:2015-07-14 18:48:26

标签: c# .net async-await

我有一个以下异步方法,它没有任何等待调用。

public async Task<bool> AddCust(Customer cust)
    {
    // doing some synchronous operations
    return true;           
    }

以下方法调用上述方法并等待结果。

public async Task<bool> ParentMethod(Customer cust)
{
 var result = await AddCust(cust);
 if(!result)
       // some logic
 return true;
}

这里的调用者,等待AddCust返回 现在,问题是我是否保留上述代码,因为它会对性能产生任何负面影响吗?如果有,为什么?

1 个答案:

答案 0 :(得分:0)

首先,您应该使用分析器来检查是否有任何重大的性能损失。

在一天结束时,@Dt是一个编译细节(也称为语法糖!),它将代码编译为常规TAP代码(任务 - 异步模式)。

顺便说一句,您的代码可以很容易地重写为:

await

最后,您应该重命名异步方法并添加public Task<bool> AddCust(Customer cust) { // If you need to perform sync operations and you also want to // retain an asynchronous TAP-based method signature you should // go this way. return Task.FromResult(true); } 后缀。例如,Async,因为它是命名约定。如果某些开发人员检查您的代码,他/她会认为它是同步操作,直到他/她意识到它返回AddCustAsync ...

IL比较

我已经实施了您的案件,我得到了最终的IL。

实际上,您可以查看Task版本的IL代码行少于Task.FromResult对应的代码:

没有async

async

使用A.Test1: IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call System.Threading.Tasks.Task.FromResult IL_0007: stloc.0 // CS$1$0000 IL_0008: br.s IL_000A IL_000A: ldloc.0 // CS$1$0000 IL_000B: ret

async

应该没有性能,但是如果你不需要简化代码就行A.Test2: IL_0000: ldloca.s 00 IL_0002: ldarg.0 IL_0003: stfld UserQuery+A+<Test2>d__0.<>4__this IL_0008: ldloca.s 00 IL_000A: call System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>.Create IL_000F: stfld UserQuery+A+<Test2>d__0.<>t__builder IL_0014: ldloca.s 00 IL_0016: ldc.i4.m1 IL_0017: stfld UserQuery+A+<Test2>d__0.<>1__state IL_001C: ldloca.s 00 IL_001E: ldfld UserQuery+A+<Test2>d__0.<>t__builder IL_0023: stloc.2 IL_0024: ldloca.s 02 IL_0026: ldloca.s 00 IL_0028: call System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>.Start IL_002D: ldloca.s 00 IL_002F: ldflda UserQuery+A+<Test2>d__0.<>t__builder IL_0034: call System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>.get_Task IL_0039: stloc.1 IL_003A: br.s IL_003C IL_003C: ldloc.1 IL_003D: ret 方式,因为没有异步在方法体中调用操作,您需要使用async方法添加额外的编译和运行时开销......

相关问题