C# 将泛型方法转换为异步导致泛型参数出现问题

C# 将泛型方法转换为异步导致泛型参数出现问题,c#,.net,generics,async-await,task-parallel-library,C#,.net,Generics,Async Await,Task Parallel Library,在名为StaticHelper的静态类中,我有以下通用的static方法: public static class StaticHelper { public static TResponse GenericMethod<TResponse, TRequest>(TRequest request, Func<TRequest, TResponse>

在名为
StaticHelper
的静态类中,我有以下通用的
static
方法:

public static class StaticHelper
{
    public static TResponse GenericMethod<TResponse, TRequest>(TRequest request,
                                                           Func<TRequest, TResponse> method)
    where TRequest  : BaseRequest
    where TResponse : BaseResponse, new()
{
    // ...
}
我现在正在尝试创建它的
async
等价物:

public static async Task<TResponse> GenericMethodAsync<TResponse, TRequest>(TRequest request,
                                                           Func<TRequest, TResponse> method)
    where TRequest  : BaseRequest
    where TResponse : BaseResponse, new()
{
    // ...
}

// i have removed the override keyword here as I don't need it
public async Task<SomeCustomResponse> Request(SomeCustomRequest request)
{
    // GenericMethodAsync above called here
    return await StaticHelper.GenericMethodAsync(request, ExecuteRequest));
}

private async Task<SomeCustomResponse> ExecuteRequest(SomeCustomRequest request)
{
    // ...
}
…很明显,解决方案就是等待:

var response = await method(request);

您需要更改
GenericMethodAsync
的声明,因为
方法
ExecuteRequest
)的返回类型现在是
Task
,而不是
treresponse

public static async Task<TResponse> GenericMethodAsync<TResponse, TRequest>(
                     TRequest request,
                     Func<TRequest, Task<TResponse>> method) // <-- change here
                            where TRequest  : BaseRequest
                            where TResponse : BaseResponse, new()
{
    // ...
}

@globetrotter如果使用
wait
,则会收到任务中方法返回的对象
。如果您使用一个简单的赋值
=
您收到有问题的任务
任务
那么返回值可以通过@MongZhu-Since-OP-make
GenericMethodAsync
一个
异步
方法访问,用
task.Result
而不是等待任务来阻止它可能是个坏主意。我不打算建议使用
Result
。只是解释了访问返回值的方法。
var response = await method(request);
public static async Task<TResponse> GenericMethodAsync<TResponse, TRequest>(
                     TRequest request,
                     Func<TRequest, Task<TResponse>> method) // <-- change here
                            where TRequest  : BaseRequest
                            where TResponse : BaseResponse, new()
{
    // ...
}
var response = await method(request);