gpt4 book ai didi

c# - 在不知道 TResult 的情况下返回 Task.ContinueWith()

转载 作者:太空狗 更新时间:2023-10-30 00:53:10 29 4
gpt4 key购买 nike

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

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

编辑:我无法更改签名类型。我有许多返回 Task< TResult > 对象的接口(interface),不能指望客户端获得 Task< Object > 结果。这些接口(interface)是 WCF 契约。我想在“核心”逻辑方法完成后做一些额外的验证逻辑,并在需要时抛出异常。此异常必须传回客户端,但目前不会传回,因为我尚未返回继续任务。另外我事先不知道类型,因为我正在应用 postsharp 方面并使用 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";
}
}
}

表达问题的另一种方式。

  1. 我只能更改 DoExtraValidation() 中的内容。
  2. 我无法更改 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();
}
}
}

最佳答案

听起来像是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);

我刚刚测试了绑定(bind)在运行时是否有效。或者,您可以使用反射来调用帮助程序(使用 MethodInfo.MakeGenericMethod 等)。

关于c# - 在不知道 TResult 的情况下返回 Task.ContinueWith<TResult>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17595915/

29 4 0