【发布时间】:2013-07-11 14:20:25
【问题描述】:
如果我只能访问任务,如何使用反射或任何其他方式创建和返回延续任务?
我需要一种方法让延续中的异常返回给原始调用者。据我所知,这只能通过返回延续任务而不是原始任务来完成。问题在于我不知道任务的结果类型,因此无法创建正确的延续任务。
编辑:
我无法更改签名类型。我有许多返回 Task
using System;
using System.Threading.Tasks;
namespace TaskContinueWith
{
internal class Program
{
private static void Main(string[] args)
{
try
{
Task<string> myTask = Interceptor();
myTask.Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
private static Task<string> Interceptor()
{
Task<string> task = CoreLogic(); //Ignore
Task unknownReturnType = task; //This is what I have access to. A Task object which can be one of numerous Task<TResult> types only known at runtime.
Task continuation = unknownReturnType.ContinueWith(
t =>
{
if(someCondition)
{
throw new Exception("Error");
}
return t.Result; //This obviously does not work since we don't know the result.
});
return continuation;
}
private static async Task<string> CoreLogic()
{
return "test";
}
}
}
表达问题的另一种方式。
- 我只能更改 DoExtraValidation() 中的内容。
- 我无法更改 DoExtraValidation() 的签名以使用泛型。
如何更改 DoExtraValidation 以使其适用于任何 Task
using System;
using System.Threading.Tasks;
namespace TaskContinueWith
{
interface IServiceContract
{
Task<string> DoWork();
}
public class Servce : IServiceContract
{
public Task<string> DoWork()
{
var task = Task.FromResult("Hello");
return (Task<string>) DoExtraValidation(task);
}
private static Task DoExtraValidation(Task task)
{
Task returnTask = null;
if (task.GetType() == typeof(Task<string>))
{
var knownType = task as Task<string>;
returnTask = task.ContinueWith(
t =>
{
if(new Random().Next(100) > 50)
{
throw new Exception("Error");
}
return knownType.Result;
});
}
return returnTask;
}
}
internal class Program
{
private static void Main(string[] args)
{
try
{
IServiceContract myService = new Servce();
Task<string> myTask = myService.DoWork();
myTask.Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
}
}
【问题讨论】:
-
为了让您的示例正常工作,unknownReturnType 任务必须是
Task<string>,因为这是您的Interceptor()方法返回的内容。总是Task<string>吗?如果是这样,那么演员表将起作用。如果没有,那么您可以返回 Task
标签: c# asynchronous task-parallel-library .net-4.5