在不知道TResult的情况下返回Task.ContinueWith <TResult>()

Ter*_*ius 4 c# asynchronous task-parallel-library .net-4.5

如果我只访问任务,如何使用反射或任何其他方式创建和返回继续任务?

我需要一种方法让延续中的异常返回原始调用者.据我所知,这只能通过返回继续任务而不是原始任务来完成.问题在于我不知道Task的结果类型,因此无法创建正确的continuation Task.

编辑:我无法更改签名类型.我有许多接口返回Task <TResult>对象,并且不能指望客户端获取Task <Object>结果.这些接口是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";
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

表达问题的另一种方式.

  1. 我只能改变DoExtraValidation()内部的内容.
  2. 我无法更改DoExtraValidation()的签名以使用泛型.

如何更改DoExtraValidation以使其适用于任何Task <TResult>返回类型?

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

usr*_*usr 5

听起来像个案子dynamic.我会尝试尽可能少地使用dynamic.首先,我们定义一个强类型的帮助器:

static Task<TResult> SetContinuation<TResult>(Task<TResult> task)
{
    return task.ContinueWith(
        t =>
            {
             if(someCondition)
             {
                 throw new Exception("Error");
             }

             return t.Result;
        });
}
Run Code Online (Sandbox Code Playgroud)

这个功能显然有效,但需要TResult知道.dynamic可以填写:

Task continuation = SetContinuation((dynamic)unknownReturnType);
Run Code Online (Sandbox Code Playgroud)

我刚刚测试了绑定在运行时的工作情况.或者,您可以使用反射来调用帮助程序(使用MethodInfo.MakeGenericMethod和其他).