Since last week, we are still continue to measuring what happens on the back end between client software and web service. On this part, we will measure execution duration of asynchorus methods over the state object. I have a custom state object and it is possible to carry this object from begin event to callback event in the same thread.

 

public class AsyncStateObject
    {
        public AsyncStateObject() { }

        public AsyncStateObject(object state)
        {
            this.State = state;
            this.StartTime = DateTime.Now;
        }

        public object State { get; set; }
        public DateTime StartTime { get; set; }
    }
With a custom AsyncStateObject class, you can pass your custom data from invoker to callback. 
And here you will see my invoker method for async web service call. _proxy object is my web service instance, so you need to change _proxy with your web service instance.
public void BeginAsyncWebServiceCall(string param)
        {
            try
            {
                IAsyncResult result = _proxy.BeginAsyncWebServiceCall(
                    param,
                    new AsyncCallback(AsyncWebServiceCallback),
                    new AsyncStateObject(param));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

And the callback method..  After casting IAsyncResult to AsyncStateObject, then you will get all of your custom properties. In here, DebugWriter is a simple txt file writer, so you can comment that line or you can use your custom log writer..

private void AsyncWebServiceCallback(IAsyncResult ar)
        {
            AsyncStateObject stateObject = (AsyncStateObject)ar.AsyncState;
            try
            {
                DebugWriter.WriteDebug("AsyncWebServiceCallback", "Duration:" + (DateTime.Now - stateObject.StartTime).TotalMilliseconds.ToString());
                string result = _proxy.EndAsyncWebServiceCall(ar);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 

Happy coding :)

If you like this, follow my RSS channel!