如果我只访问任务,如何使用反射或任何其他方式创建和返回延续任务?
我需要一种方法让延续中的异常返回原始调用者。据我所知,这只能通过返回继续任务而不是原始任务来完成。问题在于我不知道任务的结果类型,因此无法创建正确的延续任务。
编辑: 我无法更改签名类型。我有很多接口返回Task< TResult>对象并不能指望客户端获取任务<对象>结果。这些接口是WCF合同。我希望在“核心”逻辑方法完成后执行一些额外的验证逻辑,并在需要时抛出异常。此异常必须返回到客户端,但它目前不会返回,因为我还没有返回继续任务。另外我事先不知道这个类型,因为我正在应用postharp方面并使用OnExit()覆盖,这使我可以访问一个返回值,我知道这是一个Task但它可以是任意数量的Task对象TResult只在运行时才知道。
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以使其适用于任何任务&lt; TResult&gt;返回类型?
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();
}
}
}
答案 0 :(得分:5)
听起来像dynamic
的情况。我会尝试使用尽可能少的dynamic
。首先,我们定义一个强类型的帮助器:
static Task<TResult> SetContinuation<TResult>(Task<TResult> task)
{
return task.ContinueWith(
t =>
{
if(someCondition)
{
throw new Exception("Error");
}
return t.Result;
});
}
此功能显然有效,但需要知道TResult
。 dynamic
可填写:
Task continuation = SetContinuation((dynamic)unknownReturnType);
我刚刚测试了绑定在运行时的工作原理。或者,您可以使用反射来调用帮助程序(使用MethodInfo.MakeGenericMethod
和其他人)。
答案 1 :(得分:1)
您可以使用泛型(Interceptor在这里是一种扩展方法):
public static class ProjectExtensions
{
public static Task<T> Interceptor<T>(this Task<T> task)
{
Task<T> continuation = task.ContinueWith<T>(t =>
{
if(someCondition)
{
throw new Exception("Error");
}
return t.Result;
});
return continuation;
}
}
这种方式可以是任何类型的呼叫:
var t1 = new Task<string>(() => /* return string */).Interceptor();
var t2 = new Task<int>(() => /* return int */).Interceptor();