C# 等待时的影响-等待不具有任何等待调用的异步方法

C# 等待时的影响-等待不具有任何等待调用的异步方法,c#,.net,async-await,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

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

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返回
现在的问题是,如果我保持上面的代码不变,会不会对性能产生任何负面影响?若有,原因为何

首先,您应该使用探查器检查是否有任何显著的性能影响

最后,wait是一个编译细节,也称为语法糖!它将代码编译为常规TAP代码任务异步模式

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

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);           
}
使用异步
应该不会对性能造成太大的影响,但是如果在不需要简化代码的情况下采用异步方式,因为方法体中没有调用异步操作,那么可能会增加额外的编译和运行时开销,这可以使用Task.FromResult方法避免

这样写代码除了得到编译器警告不要显示之外还有什么好处吗up@SamIam我怀疑有客观优势。顺便说一句,如果可以避免的话,为什么还要增加编译开销呢?Task.FromResult毕竟应该用于您的场景…@SamIam我无法确认,但我怀疑不带异步操作的async/await可能会编译Task.FromResult。。。这是关于checkinfg使用IL disassembler、Reflector或其他工具实际编译的内容:D@SamIam检查我的答案更新关于结果IL。。。如果不执行异步操作,似乎可以避免使用异步方法…:请记住,在这两种方法下,异常行为是不同的。请怀疑XY问题。你为什么要这么做?请注意,编译器会给您一个警告,因为对于您尝试执行的任何操作,代码几乎肯定是错误的解决方案。
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  
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