在不知道T-postharp的情况下访问Task <t>的结果

时间:2017-01-06 16:05:10

标签: c# task postsharp

我正在尝试使用postharp修改异步方法的返回值。是否可以在不知道T的情况下在运行时获取Task的结果?

public void OnSuccess(MethodExecutionArgs args)
{

var returnValue = args.ReturnValue;

// returnType is Task<T>
var returnType = returnValue.GetType();    

// Is it possible to access the result of the task?

// If T was known then I could cast:
// ((Task<T>) returnValue).ContinueWith(t => t.Result ...)
}

1 个答案:

答案 0 :(得分:1)

如果没有反思,您需要使用和界面。同样使用PostSharp 5.0,您可以使用OnSuccess方法而不是Task<>获取结果。

此示例适用于PostSharp 5.0:

using System;
using System.Threading.Tasks;
using PostSharp.Aspects;
using PostSharp.Serialization;

namespace OnMethodBoundaryAsyncTest
{
    interface IDirtiness
    {
        bool Dirty { get; set; }
    }

    class MyClassWithSomeDirtyObjects : IDirtiness
    {
        public bool Dirty { get; set; }
    }

    [PSerializable]
    class ReportDirtinessAttribute : OnMethodBoundaryAspect
    {
        public override void OnSuccess( MethodExecutionArgs args )
        {
            IDirtiness maybeDirtyObject = args.ReturnValue as IDirtiness;

            if ( maybeDirtyObject != null )
            {
                string dirty = maybeDirtyObject.Dirty ? "is" : "is not";
                Console.WriteLine($"{maybeDirtyObject} {dirty} dirty.");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CreateObject( false ).GetAwaiter().GetResult();
            CreateObject( true ).GetAwaiter().GetResult();
        }

        [ReportDirtiness(ApplyToStateMachine = true)]
        static async Task<MyClassWithSomeDirtyObjects> CreateObject( bool dirty )
        {
            return new MyClassWithSomeDirtyObjects {Dirty = dirty};
        }
    }
}