ExecutionContext of Threads

S M Kamran picture S M Kamran · Dec 23, 2009 · Viewed 12.9k times · Source

What's the purpose of ExecutionContext.SuppressFlow();? In the following code what exactly gets suppressed?

I've this test code...

protected void btnSubmit_Click(object sender, EventArgs e)
{
   Thread[] th = new Thread[100];
   Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");

   AsyncFlowControl cntrl = ExecutionContext.SuppressFlow();
   for (int i = 0; i < th.Length; i++)
   {                   
      th[i] = new Thread(new ParameterizedThreadStart(ThreadMethod));
      th[i].Name = "Thread #" + (i+1).ToString();                
      th[i].Start((i+1).ToString());
   }
   ExecutionContext.RestoreFlow();

   foreach (Thread t in th)            
   {
      t.Join();
   }
   Response.Write(response);
}


String response = null;
Random rnd = new Random(1000);
private void ThreadMethod(object param)
{   
   if (param != null)
   {
      string temp = param as string;
      if (temp != null)
      {
         //To test what is the current culture I get for this thread execution
         System.Globalization.CultureInfo info = Thread.CurrentThread.CurrentCulture;
         for (int i = 0; i <= 10; i++)
         {
            Thread.Sleep(rnd.Next(2000));
            response += Thread.CurrentThread.ManagedThreadId.ToString() + ":" 
                     + Thread.CurrentThread.Name + ": " + temp + "<br/>";
         }
      }
   }
}

Answer

serhio picture serhio · Dec 23, 2009

ExcecutionContext.SuppressFlow suppresses the flow of the execution context across asynchronous threads.

The ExecutionContext, are implicitly passed from parent thread to the child one, provides information relevant to a logical thread of execution: security context, call context and synchronization context. If that information is not imperative, the omission of the execution context optimize a little the performance of a multithreading application.

ExecutionContext.RestoreFlow restores the passage of the execution context between threads.

Finally

Q: In the following code what exactly gets suppressed??

A: Exactly are suppressed the passage of the following information: security context, call context and synchronization context; between the newly created threads. Why that was do? -To optimize the creation and work of th.Length created threads: less supplementary information passed between threads - quicker this threads interact between them.