我有一个同步的、通用的方法,如下所示
public TResponse Execute<TResponse>(Request request) where TResponse : Response
{
return (TResponse) proxy.ExecuteRequest(request);代理是WCF服务引用。
它只有一个接收请求并返回响应的方法。但是它是通过传递派生请求和返回派生响应来使用的。如上文所示,包装器方法将响应转换为泛型参数(TResponse)指定的派生类型。
使用派生的请求和响应调用方法。
例如:
Execute<GetSomeDataResponse>(new GetSomeDataRequest());我现在正在生成一个异步服务引用,这样就可以使用任务。
所以我想要一种像这样的方法
public Task<TResponse> ExecuteAsync<TResponse>(Request request) where TResponse : Response
{
// need to cast to a Task<TResponse>
return proxy.ExecuteRequestAsync(request可以这样称呼
Task<GetSomeDataResponse> res = ExecuteAsync<GetSomeDataResponse>(new GetSomeDataRequest());因此,我需要一种将Task<Response>转换为Task<TResponse>的方法
我一直在读这篇文章,这似乎与我所需要的完全相反,但我不太明白如何将它转化为用例。
有什么想法吗?
发布于 2016-05-13 15:18:24
简单的方法是使用异步\等待模式:
public static async Task<TResponse> ExecuteAsync<TResponse>(Request request) where TResponse : Response {
var response = await proxy.ExecuteRequestAsync(request);
return (TResponse) response;
}更复杂的(摘自您的链接问题)是使用TaskCompletionSource
public static Task<TResponse> ExecuteAsync2<TResponse>(Request request) where TResponse : Response {
var tcs = new TaskCompletionSource<TResponse>();
proxy.ExecuteRequestAsync(request).ContinueWith(t => {
if (t.IsFaulted)
tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled)
tcs.TrySetCanceled();
else
tcs.TrySetResult((TResponse) t.Result);
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}https://stackoverflow.com/questions/37213557
复制相似问题