如何以编程方式跟踪响应持续时间?

时间:2013-09-01 09:04:24

标签: c# wcf

客户端调用我的Web WCF服务的方法“Foo()” - 并接收大字节数组作为响应:

public byte[] Foo()
{
    return new byte[10000000];
}

显然,当客户端读取所有数据时,HTTP连接被关闭 - 如果我知道这是什么时候发生的,我可以跟踪“传输”的总持续时间。我知道跟踪等 - 但我需要以编程方式获取此数据,因此我可以将其显示给用户。我该如何追踪?

2 个答案:

答案 0 :(得分:0)

我有两个解决方案,性能计数器和自定义行为,但我不确定他们是否完全回答了您的问题,因为我没有考虑网络延迟。

效果计数器
第一个解决方案使用内置的performance counters,它接近您的要求。 基本上,您希望为您的服务启用performanceCounters,然后在您的服务中获取其中一个。确切的持续时间不可用,但Calls per second是其他计数器。

确保将其添加到您的服务配置中:

<system.serviceModel>
    <diagnostics performanceCounters="All" />
</system.serviceModel>

在您的服务中有一个静态类,用于保存您的performancecounter。在我的示例中,我将静态实例添加到服务中,实际上我会将其移动到另一个类。

public class Service1 : IService1
{
     // in an ideal world thisd how instancename would look like
    //ServiceName.ContractName.OperationName@first endpoint listener address

    private static PerformanceCounter pc = new PerformanceCounter();

     // our static constructor
    static Service1()
    {
        // naming of the instance is garbeld due to length restrictions...
        var cat = new PerformanceCounterCategory("ServiceModelOperation 4.0.0.0");
        foreach (var instance in cat.GetInstanceNames())
        {
            Trace.WriteLine(instance); // determine the instancename and copy over :-)
        }
        pc.CategoryName = "ServiceModelOperation 4.0.0.0";
        pc.CounterName = "Calls Per Second";
        pc.InstanceName = "Service1.IServ84.GetDataUsingD31@00:||LOCALHOST:2806|SERVICE1.SVC";

    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        // do interesting stuff here

        // here I have the value (in the service call but you can call this from anywhere, 
        // even from another thread. 
        // or use perfmon.exe to obtain or make a graph of the value over time...
        Trace.WriteLine(pc.NextValue().ToString()); 

        return composite;
    }
}

自定义行为
此自定义行为拦截了servicemethod的调用,并且可以启动和停止计时器并存储结果。

添加以下课程:

// custom self timing for any wcf operation
    public class Timing :Attribute, IOperationBehavior,  IOperationInvoker 
    { 
        IOperationInvoker innerOperationInvoker;
        private string operName = "";

        public Timing()
        {
        }

        public Timing(IOperationInvoker innerOperationInvoker, string name)
        {
            this.innerOperationInvoker = innerOperationInvoker;
            operName = name;
        }

        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            dispatchOperation.Invoker = new Timing(dispatchOperation.Invoker, operationDescription.Name);
        }

        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            object value;

            var sw = new Stopwatch();
            sw.Start();
            value = innerOperationInvoker.Invoke( instance, inputs, out outputs);
            sw.Stop();
            // do what you need with the value...
            Trace.WriteLine(String.Format("{0}: {1} ms", operName,  sw.ElapsedMilliseconds));
            return value;
        }


        // boring required interface stuff

        public object[] AllocateInputs()
        {
            return innerOperationInvoker.AllocateInputs();
        }

        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            return innerOperationInvoker.InvokeBegin(instance, inputs, callback, state);
        }

        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            return innerOperationInvoker.InvokeEnd(instance, out outputs, result);
        }

        public bool IsSynchronous
        {
            get { return innerOperationInvoker.IsSynchronous; }
        }

        public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            // throw new NotImplementedException();
        }

        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
            // throw new NotImplementedException();
        }

        public void Validate(OperationDescription operationDescription)
        {
            // throw new NotImplementedException();
        }
    }

现在在您的界面中装饰您想要使用Timing属性存储其计时的操作:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [Timing]   // Timing for this Operation!
    CompositeType GetDataUsingDataContract(CompositeType composite);
}

答案 1 :(得分:-1)

您可以使用StopWatch类来查找持续时间,请参阅此msdn链接:

http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.elapsed.aspx

        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        // your wcf functionalities
        stopWatch.Stop();
        long duration = stopWatch.ElapsedMilliseconds;