view Implab/Diagnostics/TraceContext.cs @ 92:4c0e5ef99986 v2

rewritten tracing
author cin
date Wed, 22 Oct 2014 18:37:56 +0400
parents c761fc982e1d
children dc4942d09e74
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.Threading;

namespace Implab.Diagnostics {
    /// <summary>
    /// Trace context is bound to the specific thread, each thread has it's own ThreadContext.
    /// </summary>
    /// <remarks>
    /// ThreadContext manages relations between logical operations and threads.
    /// </remarks>
    public class TraceContext {

        [ThreadStatic]
        static TraceContext _instance;

        OperationContext m_current = OperationContext.EMPTY;
        readonly Stack<OperationContext> m_stack = new Stack<OperationContext>();
        readonly int m_threadId;

        public static TraceContext Instance {
            get {
                if (_instance == null)
                    _instance = new TraceContext();
                return _instance;
            }
        }

        public TraceContext() {
            m_threadId = Thread.CurrentThread.ManagedThreadId;
        }

        public int ThreadId {
            get { return m_threadId; }
        }

        public LogicalOperation CurrentOperation {
            get {
                return m_current.CurrentOperation;
            }
        }

        public void EnterLogicalOperation(LogicalOperation operation, bool takeOwnership) {
            // TODO Emit event
            m_stack.Push(m_current);
            m_current = new OperationContext(operation, takeOwnership);
        }

        public void StartLogicalOperation(string name) {
            m_current.BeginLogicalOperation(name);
        }

        public void StartLogicalOperation() {
            // TODO Emit Event
            m_current.BeginLogicalOperation(String.Empty);
        }

        public void EndLogicalOperation() {
            // TODO Emit event
            m_current.EndLogicalOperation();
        }

        public LogicalOperation DetachLogicalOperation() {
            // TODO Emit event
            return m_current.DetachLogicalOperation();
        }

        public void Leave() {
            // TODO Emit event
            if (m_stack.Count > 0)
                m_current = m_stack.Pop();
            else {
                TraceLog.TraceWarning("Attemtp to leave the last operation context");
                m_current = OperationContext.EMPTY;
            }
        }
    }
}