如何創建並返回繼續任務使用反射或通過任何其他方式,如果我只有訪問任務?返回Task.ContinueWith <TResult>()不知道TResult
我需要一種方法來讓繼續中的異常傳回原始調用者。據我所知,這隻能通過返回繼續任務而不是原始任務來完成。問題在於我不知道任務的結果類型,因此無法創建適當的延續任務。
編輯: 我無法更改簽名類型。我有很多接口返回任務< 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()裏面的內容。
- 我無法更改DoExtraValidation()的簽名以使用泛型。
如何更改DoExtraValidation以使其適用於任何任務< 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();
}
}
}
爲了讓你的榜樣工作,unknownReturnType任務必須是'Task',因爲這是你的'Interceptor()'方法返回的。它總是一個任務'?如果是這樣,那麼演員陣容將工作。如果沒有,那麼你可以返回任務