3

我一直在[<Trace>]为我们的一些大型 .NET 解决方案实现一个属性,该属性将允许将可配置分析轻松添加到任何被认为重要的功能/方法中。我正在使用 Fody 和MethodBoundaryAspect来拦截每个函数的进入和退出并记录指标。这对于同步函数很有效,对于返回的方法,Task有一个可行的解决方案Task.ContinueWith,但对于 F# Async-returning 函数,OnExit来自 MethodBoundaryAspect 的 将在 Async 返回后立即运行(而不是在实际执行 Async 时)。

为了捕获 F# Async-returning 函数的正确指标,我试图想出一个等效的解决方案 using Task.ContinueWith,但我能想到的最接近的事情是创建一个绑定第一个 Async 的新 Async ,运行指标-捕获函数,然后返回原始结果。由于我截获的 F# Async 返回值仅以obj.知道确切的返回类型。AsyncTask

到目前为止,我最好的解决方案大致如下:

open System
open System.Diagnostics
open FSharp.Reflection
open MethodBoundaryAspect.Fody.Attributes

[<AllowNullLiteral>]
[<AttributeUsage(AttributeTargets.Method ||| AttributeTargets.Property, AllowMultiple = false)>]
type TraceAttribute () =
    inherit OnMethodBoundaryAspect()

    let traceEvent (args: MethodExecutionArgs) (timestamp: int64) =
        // Capture metrics here
        ()

    override __.OnEntry (args) =
        Stopwatch.GetTimestamp() |> traceEvent args

    override __.OnExit (args) =
        let exit () = Stopwatch.GetTimestamp() |> traceEvent args
        match args.ReturnValue with
        | :? System.Threading.Tasks.Task as task ->
            task.ContinueWith(fun _ -> exit()) |> ignore             
        | other -> // Here's where I could use some help
            let clrType = other.GetType()
            if clrType.IsGenericType && clrType.GetGenericTypeDefinition() = typedefof<Async<_>> then
                // If the return type is an F# Async, replace it with a new Async that calls exit after the original return value is computed
                let returnType = clrType.GetGenericArguments().[0]
                let functionType = FSharpType.MakeFunctionType(returnType, typedefof<Async<_>>.MakeGenericType([| returnType |]))
                let f = FSharpValue.MakeFunction(functionType, (fun _ -> exit(); other))
                let result = typeof<AsyncBuilder>.GetMethod("Bind").MakeGenericMethod([|returnType; returnType|]).Invoke(async, [|other; f|]) 
                args.ReturnValue <- result
            else
                exit()

不幸的是,这个解决方案不仅非常混乱,而且我相信异步计算的反射结构增加了不小的开销,特别是当我试图跟踪在循环中调用或深度嵌套的函数时异步调用。是否有更好的方法可以在实际评估异步计算后立即运行给定函数的相同结果?

4

2 回答 2

2

像这样的东西可能是你需要的:

let traceAsync (a:Async<_>) = async {
    trace() // trace start of async
    let! r = a
    trace() // trace end of async
    return r
}

考虑一下,当一个函数返回一个异步并不意味着异步已经开始。异步更像是一个函数,它可以被调用多次或根本不调用。这意味着您还需要在您的OnEntry方法中检查返回值是否为 Async。

于 2019-03-21T23:59:16.123 回答
0

遵循@AMieres 的建议,我能够更新我的OnExit方法以正确跟踪异步执行,而无需太多开销。我认为大部分问题实际上是在使用相同的实例AsyncBuilder,这导致异步函数的额外调用。这是新的解决方案:

open System
open System.Diagnostics
open FSharp.Reflection
open MethodBoundaryAspect.Fody.Attributes

[<AllowNullLiteral>]
[<AttributeUsage(AttributeTargets.Method ||| AttributeTargets.Property, AllowMultiple = false)>]
type TraceAttribute () =
    inherit OnMethodBoundaryAspect()
    static let AsyncTypeDef = typedefof<Async<_>>
    static let Tracer = typeof<TraceAttribute>
    static let AsyncTracer = Tracer.GetMethod("TraceAsync")

    let traceEvent (args: MethodExecutionArgs) (timestamp: int64) =
        // Capture metrics here
        ()

    member __.TraceAsync (asyncResult: Async<_>) trace =
        async {
            let! result = asyncResult
            trace()
            return result
        }

    override __.OnEntry (args) =
        Stopwatch.GetTimestamp() |> traceEvent args

    override __.OnExit (args) =
        let exit () = Stopwatch.GetTimestamp() |> traceEvent args
        match args.ReturnValue with
        | :? System.Threading.Tasks.Task as task ->
            task.ContinueWith(fun _ -> exit()) |> ignore             
        | other -> 
            let clrType = other.GetType()
            if clrType.IsGenericType && clrType.GetGenericTypeDefinition() = AsyncTypeDef then
                let generics = clrType.GetGenericArguments()
                let result = AsyncTracer.MakeGenericMethod(generics).Invoke(this, [| other; exit |])
                args.ReturnValue <- result
            else
                exit()

这似乎可以正确地跟踪异步函数,而开销要少得多。我确实想跟踪调用函数时的总时间,而不是异步实际开始时的总时间,所以我让我的OnEntry实现保持不变。

于 2019-03-22T14:11:52.013 回答