为什么这个异步方法没有编译错误?

Why does this async method not have a compile error?

可能是我对标记为async的方法在编译过程中发生的情况缺乏了解,但为什么该方法可以编译?

    public async Task<bool> Test()
    {
        return true;
    }

只是在这里寻找解释,这样我才能更好地理解发生了什么。 Task 会自动换行吗?为什么允许这种方法? (它不遵守方法签名,即 return a Task<bool>)。

更新: 看来这也适用于以下参数:

    public void Main()
    {
        Input(Test);
    }

    public async Task<bool> Test()
    {
        return true;
    }

    public void Input(Func<Task<bool>> test)
    {

    }

其中,测试方法 return 是一个 Task 隐式。

你可以看看你代码的反编译版本here

using System;
public class C {
    public async System.Threading.Tasks.Task<bool> M() {
        return false;
    }
}

该方法被编译成一个普通的异步方法,有了状态机,它毕竟return一个Task<bool>

public class C
{
    [CompilerGenerated]
    private sealed class <M>d__0 : IAsyncStateMachine
    {
        public int <>1__state;

        public AsyncTaskMethodBuilder<bool> <>t__builder;

        public C <>4__this;

        //called when you awaiting the Task
        void IAsyncStateMachine.MoveNext()
        {
            int num = this.<>1__state;
            bool result;
            try
            {
                result = false;  //the result is set
            }
            catch (Exception arg_0C_0)
            {
                Exception exception = arg_0C_0;
                this.<>1__state = -2;
                this.<>t__builder.SetException(exception);
                return;
            }
            this.<>1__state = -2;
            this.<>t__builder.SetResult(result); 
        }

        [DebuggerHidden]
        void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
        {
        }
    }

    [DebuggerStepThrough, AsyncStateMachine(typeof(C.<M>d__0))]
    public Task<bool> M()
    {
        // the state machine instance created
        C.<M>d__0 <M>d__ = new C.<M>d__0(); 
        <M>d__.<>4__this = this;
        <M>d__.<>t__builder = AsyncTaskMethodBuilder<bool>.Create();
        <M>d__.<>1__state = -1;
        AsyncTaskMethodBuilder<bool> <>t__builder = <M>d__.<>t__builder;
        <>t__builder.Start<C.<M>d__0>(ref <M>d__);
        return <M>d__.<>t__builder.Task;
    }
}

顺便说一句,编译器会给你一个警告,因为你从来没有在你的方法中 await:

warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

你完全正确,你可以 return 完成任务:

using System;
using System.Threading.Tasks;
public class C {
    public Task<bool> M() {
        return Task.FromResult(false); //no need to await here at all
    }

}

上述方法的其他编码方式could be found here

using System;
using System.Threading.Tasks;
public class C {
    public async Task<bool> M() {
        return false;
    }

    public async Task<bool> M2(){
        return await Task.FromResult(false);
    }

    public Task<bool> M3(){
        return Task.FromResult(false);
    }
}

我希望这会为您澄清一些事情。