Execution context

        1. What is the thread execution context?

        2. Why do we need to optimize the thread execution contexts?

Every thread has the execution context data structure associated with it. The execution context contains such settings as security settings (Thread principal property and Windows identity), host settings (HostExecutionContextManager) and logical call context data (CallContext Class).

There is a performance issue due to copying thread context data from the initial thread to a helper thread. We can suppress the flow of thread context data using the ExecutionContext class and its method ExecutionContext.SuppressFlow()

Sample 1:

        static void Main(string[] args)

        {

            //Put some data into the Main’s thread logical context

            CallContext.LogicalSetData(“Key”, “Value”);

            string[] rolesArray = { “managers”, “executives” };

            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(“Bob”, “Passport”), rolesArray);

            //Now we can get data from the Main’s thread logical context

            ThreadPool.QueueUserWorkItem(

                state =>

                {

                    Trace.WriteLine(“The helper’s thread context allowed to copy the main’s thread context”);

                    Trace.WriteLine(String.Format(“Call context data: {0}”, CallContext.LogicalGetData(“Key”)));

                    Trace.WriteLine(String.Format(“Thread.CurrentPrincipal.Identity.Name: {0}”, Thread.CurrentPrincipal.Identity.Name));

                }

            );

            //Now, let’s do some optimization and suppress the flow of the Main’s thread execution context

            ExecutionContext.SuppressFlow();

            //So now, since we have suppressed the flow of the Main’s thread execution context, we can’t get any data

            ThreadPool.QueueUserWorkItem(

                state =>

                {

                    Trace.WriteLine(“Suppressed flow”);

                    Trace.WriteLine(String.Format(“Call context data: {0}”, CallContext.LogicalGetData(“Key”)));

                    Trace.WriteLine(String.Format(“Thread.CurrentPrincipal.Identity.Name: {0}”, Thread.CurrentPrincipal.Identity.Name));

                }

            );

            //Let’s other threads to get access to the thread logical context

            ExecutionContext.RestoreFlow();

            Console.ReadKey();

        }

Output:

Suppressed flow

Call context data:

Thread.CurrentPrincipal.Identity.Name:

The helper’s thread context allowed to copy the main’s thread context

Call context data: Value

Thread.CurrentPrincipal.Identity.Name: Bob

Advertisements