LOOM.NET 是波茨坦大学的一个研究项目, 它采用 Emit IL 的方式实现代码与Aspect的编织, 现在有两个子项目, 分别是Runtime weaver: Rapier-LOOM.NET 和 Static weaver: Gripper-LOOM.NET.
下面的示例代码演示了如何使用 Rapier-LOOM.NET 来监视一个方法的运行时间

using System;

using System.Collections.Generic;

using System.Text;

 

using Loom;

using Loom.JoinPoints;

 

namespace Monitoring

{

    class Program

    {

        static void Main(string[] args)

        {

            MonitoringAspect monAspect = new MonitoringAspect();

 

            // interweave with the monitoring aspect

            MathLibrary lib = Weaver.Create<MathLibrary>(monAspect);

 

            ulong number = 30;

 

            Console.WriteLine("Computing {0}. fibonacci number.", number);

 

            // monitoring aspect calculates the time of execution

            // and display on the console

            ulong result = lib.Fibonacci(number);

 

            Console.WriteLine("Result is {0}.", result);

            Console.Read();

        }

    }

 

    public class MathLibrary

    {

        public virtual ulong Fibonacci(ulong a)

        {

            return calcFibonacci(a);

        }

 

        // private methods - not matched

        private ulong calcFibonacci(ulong a)

        {

            if (a > 40)

                throw new ApplicationException("Error: Can only compute the first 40 fibonacci numbers.");

 

            if (a <= 2)

                return 1;

            else

                return (calcFibonacci(a - 1) + calcFibonacci(a - 2));

        }

    }

 

    public class MonitoringAspect : Aspect

    {

        [IncludeAll]

        [Call(Advice.Before)]

        public void Start_Monitor([JPContext] Context context, params object[] args)

        {

            Stopwatch sw = new Stopwatch();

            sw.Start();

            context.Tag = sw;

        }

 

        [IncludeAll]

        [Call(Advice.After)]

        public void Stop_Monitor([JPContext] Context context, params object[] args)

        {

            Stopwatch sw = (Stopwatch)context.Tag;

            sw.Stop();

            Console.WriteLine("{0} done in {1}ms.", context.CurrentMethod.Name, sw.ElapsedMilliseconds);

        }

    }

}


LOOM.NET 主页
Posted on 2007-06-27 13:58  Adrian H.  阅读(922)  评论(0编辑  收藏  举报