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-makeGenericMethodAsync
一个异步
方法访问,用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);