One mighty gotcha for System.Diagnostic activity Ids

by Matt 14. August 2007 06:28

I've been scratching my head on this one for several days.

After spending a number of posts looking at System.Diagnostics for tracing, and especially at the concept of activity IDs, I decided to put into a project I'm working on. And it all went wrong.

Here's the scenario. I have a WPF application. At start up, it goes straight into a business process that is neatly encapsulated in a model-view-presenter style, written using the Supervising Controller pattern (well, WPF's databinding is so powerful and so pervasive, it'd be rude not to). When I spin up my controller, I create and transfer to a new activity. Events logged at this point correctly live in the new activity.

When I click a button to make something happen, a (custom) event is raised from the view, and handled by the controller. Events logged here are suddenly not part of the activity. The activity Id has been reset to a zero guid.

From the msdn docs on CorrelationManager:

The CorrelationManager class provides methods used to store a logical operation identity in a thread-bound context and automatically tag each trace event generated by the thread with the stored identity.

So obviously my first thought was that this is a threading issue. Turns out it is, but not how you'd expect.

I verified that the thread I started the activity on and the thread used to execute the event handlers were the same, so they should really have the same activity Id.

A serious session of spelunking with Reflector later (and I do mean serious), I had my answer. The CorrelationManager uses Remoting's CallContext to store the activity Id (which has the nice side effect of being transferred across AppDomain boundaries, propagating the activity Id). Cutting a long story short, the data set via the CallContext ends up (indirectly) in an instance of a class called ExecutionContext.

And it's ExecutionContext that causes all the trouble. Again, from the msdn docs:

The ExecutionContext class provides a single container for all information relevant to a logical thread of execution.

The key word there is "logical".

Ever wondered how your security impersonation data is transferred between threads? What about your call stack for Code Access Security? Yep. ExecutionContext.

Every time you start a thread or queue an operation on the thread pool, the current ExecutionContext is carried with it. This is really rather cool when you think about it.

How does that cause problems for me? Well, WPF, like Windows Forms, needs to marshal calls onto the correct thread to prevent deadlocks. That needs an ExecutionContext. If the ExecutionContext is grabbed before I make my change to the activity Id, it won't get propagated. The existing ExecutionContext, which contains the previous, empty activity Id will be used. Practically, this means that all event handlers run under an ExecutionContext created by WPF, and it's this ExecutionContext I am seeing as having no activity Id. And the ExecutionContext is used even if you're already on the correct thread - presumably for CAS and impersonation reasons.

I can see two ways to fix this problem. If you noticed in the description of my problem - I was starting the activity in code that got evaluated from Main, not from the message pump. If I set it from the message pump, I think I'd be using the same ExecutionContext that WPF uses for the event handlers. I suspect that would look something like:

Dispatcher.Invoke(DispatcherPriority.Normal, delegate {
  _previousActivityId = Trace.CorrelationManager.ActivityId;
  Guid newActivityId = Guid.NewGuid();
  _traceSource.TraceTransfer(0, null, newActivityId);
  Trace.CorrelationManager.ActivityId = newActivityId;
  _traceSource.TraceEvent(TraceEventType.Start, 0, "New activity");
});

But I haven't tried it, so can't be sure - I don't actually know where the WPF ExecutionContext gets created, or even how often it gets created. Relying on this is too flaky for my liking. (But I do like how elegant it is to be able to execute an arbitrary anonymous delegate on the UI thread. Just try doing that in Win32.)

As usual, we can solve this by adding an extra level of abstraction. I think I'm going to add a new class that will encapsulate starting and transferring an activity. All logging will go through this, too, and before each log it will check that the current activity is the correct one. If not, it will set it, log the event and reset it back to what it was. Simple, and effective.

Just to be clear, this won't be a problem for most uses of activities. If you have a bounded activity - i.e. if you both start and stop the activity in a single method, then you'll always be on a single thread of execution, always using the same ExecutionContext and all will be good. If you start an activity and then queue up an operation on the thread pool, the current ExecutionContext (with the current activity Id) will go with it, and again, all will be good. You're only going to have a problem when you have pieces of your activity executing in different contexts, such as with Windows Forms or WPF event handlers.

Tags:

Comments (69) -

ledsi its alright
ledsi its alright
5/29/2011 12:28:43 AM #

Not the longest post, but then again my LED site hasn't much either, and a default design - Great post all around, added your XML feed! Cheers

Reply

suv review
suv review
7/20/2011 10:33:40 PM #

Hi, just required you to know I he added your website to my Google bookmarks due to your layout. But seriously, I consider your net web-site has 1 in the freshest theme I??ve came across. It extremely helps make studying your blogging site significantly easier.

Reply

first direct loans
first direct loans
8/2/2011 8:59:00 PM #

Hi,what an excellent article this is,I found it on bing and I like it very much,I agree with what you have said, lots of things will be learned form your site,but I still have some questions with the last part,can you explain it for me ?I will appreciate your answer,and I will be back again!

Reply

burberry outlet
burberry outlet
9/19/2011 3:08:52 PM #

Comparing with the bright color 2011 autumn and winter series, the color of this season men's clothing series is still rich, but more dull and strong. Men's dust coat has wide chrysalis or box outline, collars of many patterns uses crochet and decorated with small pearls. <a href="http://www.burberrylondonsale.com"; >burberry london</a>  <a href="http://www.burberrylondonsale.com"; >burberry sale</a>  <a href="http://www.burberrylondonsale.com"; >burberry wallet</a>  <a href="http://www.burberrylondonsale.com"; >cheap burberry</a>
Related:

Reply

Btissam
Btissam
10/22/2011 10:02:26 AM #

hello there,

Nice, post here will came back
continue updating your blog

Reply

Btissam
Btissam
10/23/2011 11:58:34 AM #

hi,

Nice, post here will came back

Reply

Eric
Eric
10/23/2011 7:26:07 PM #

Hello

Interresting post here will came back
continue updating your blog

Reply

Robert
Robert
10/23/2011 8:46:18 PM #

hello there,

Interresting post here will came back
Keep like this

Reply

Btissam
Btissam
10/23/2011 10:53:20 PM #

hello there,

Interresting post here will came back
Keep like this

Reply

Stephane
Stephane
10/24/2011 12:22:03 AM #

Hi

Interresting post here will came back

Reply

proto
proto United States
10/27/2011 4:35:21 AM #

hi, this is my comment

Reply

proto
proto United States
10/27/2011 4:37:57 AM #

hi, this is my comment

Reply

Adirondack Boot outlet
Adirondack Boot outlet
10/30/2011 4:59:39 AM #

Actually,I have been so long standing behind you, lacking of your turning round.

Reply

solar360
solar360 United States
5/18/2015 2:54:47 PM #

I have a project that I am just now working on, and I have been looking for such information... Regards

Reply

philix
philix United States
11/20/2015 9:41:49 AM #

Nice Web Site.

Reply

philix
philix United States
11/20/2015 9:56:37 PM #

wonderful website.

Reply

philix
philix United States
11/21/2015 2:39:14 AM #

great website.

Reply

Philix
Philix United States
11/23/2015 2:47:23 AM #

Superb Site.

Reply

Philix
Philix United States
11/23/2015 2:48:22 AM #

Great Site

Reply

philix
philix United States
11/27/2015 6:05:34 PM #

nice website

Reply

link building services
link building services United States
12/14/2015 12:44:58 AM #

Legendary! This is just outstanding! Not simply quality, however likewise useful information. Which is rare ahead by nowadays! I need to state that I am truly pleased as well as will definitely return once more if you maintain the high quality and also worth of the content at this level, or maybe acquire it on the following degree. Regards, from all-time low of my heart, thanks for your time! God bless!

Reply

Hilaria Rieff
Hilaria Rieff United States
1/15/2016 3:43:51 AM #

Well good for you! I have a lot but one I just thought of was when you lick a crease of paper so that it'll rip in a straight line and it actually tears in a frayed straight line rather than rips awkwardly. I love that bleachy taste and that bleachy satisfaction.

Reply

Luvenia Colier
Luvenia Colier United States
1/15/2016 3:47:56 AM #

getting laid AWSOME

Reply

Rosario Carello
Rosario Carello United States
1/15/2016 4:04:07 AM #

The dolphin saving you one is the best one!

Reply

Walter Rigsbee
Walter Rigsbee United States
1/15/2016 4:13:08 AM #

getting laid AWSOME

Reply

Hilaria Rieff
Hilaria Rieff United States
1/15/2016 4:15:26 AM #

getting the last pair of shoes in your size AWESOME!

Reply

Loren Benward
Loren Benward United States
1/15/2016 4:21:00 AM #

Printing out an essay or paper, reading the first line and realizing there aren't any mistakes.<br />AWESOME!

Reply

Stanley Tocci
Stanley Tocci United States
1/15/2016 4:51:24 AM #

I love the dolphin saving you one.

Reply

Douglas Ramler
Douglas Ramler United States
1/15/2016 4:58:05 AM #

I can't wait to read this masterpiece. Ordering off the menu at fast food restaurants and old dangerous playground equipment have to be in the book!

Reply

Herbert Britson
Herbert Britson United States
1/15/2016 5:07:52 AM #

AWESOME!Can't wait for that, will be something to want to accomplish day by day, to do something AWESOME!

Reply

Lidia Loser
Lidia Loser United States
1/15/2016 5:45:28 AM #

Let me be the first to say: Congrats, Neil! I've been following this site from day one, and have loved every single day of awesomeness that it has delivered. You deserve all the success coming your way. Keep it up!AWESOME!

Reply

Hilaria Rieff
Hilaria Rieff United States
1/15/2016 6:39:21 AM #

Thaaaat IS awesome! lol hehe

Reply

Lashawn Ulwelling
Lashawn Ulwelling United States
1/15/2016 6:58:58 AM #

getting laid AWSOME

Reply

Palmer Rinck
Palmer Rinck United States
1/15/2016 7:44:46 AM #

I love the dolphin saving you one.

Reply

Blake Krist
Blake Krist United States
1/15/2016 7:51:07 AM #

the style of keeping you connected with so many things of different types is awesome and you find it interesting everytime.

Reply

Sharri Michonski
Sharri Michonski United States
1/15/2016 8:27:38 AM #

I can't wait to read this masterpiece. Ordering off the menu at fast food restaurants and old dangerous playground equipment have to be in the book!

Reply

Riley Laurino
Riley Laurino United States
1/17/2016 9:54:10 PM #

Congrats! So glad to see this site getting the recognition it deserves, the world can always use a little more awesome.

Reply

Francesca Vilardo
Francesca Vilardo United States
1/19/2016 10:28:35 PM #

Well good for you! I have a lot but one I just thought of was when you lick a crease of paper so that it'll rip in a straight line and it actually tears in a frayed straight line rather than rips awkwardly. I love that bleachy taste and that bleachy satisfaction.

Reply

high pr backlinks for yahoo
high pr backlinks for yahoo United States
1/26/2016 12:11:30 AM #

Wow! Merely amazing! Thanks a lot for the information shared! I know you have placed a lot of effort right into this as well as I wished to inform you exactly how happy I am! There need to be much more blog sites such as this online! I will certainly subscribe and also bookmark to your superior website! Hope you put out much more incredible things in the soon and also I will return and also read it! Keep up the magnum opus!

Reply

buy backlinks
buy backlinks United States
2/9/2016 8:23:24 PM #

Simply incredible! I recognize you have actually put a lot of effort into this as well as I desired to tell you just how grateful I am! Hope you put out also much more spectacular stuff in the close to future as well as I will certainly come back as well as read it!

Reply

POŻYCZKA
POŻYCZKA United States
6/23/2016 9:06:08 AM #

Pożyczka gotówkowa

Reply

REJESTRACJA DOMEN
REJESTRACJA DOMEN United States
6/25/2016 7:23:28 AM #

rejestracja domen

Reply

rejestracja domen
rejestracja domen United States
6/25/2016 8:37:08 AM #

Rejestracja Domen

Reply

Violette Currie
Violette Currie United States
7/20/2016 6:57:48 AM #

"great threat, i like it, thanks very_ much."

Reply

James Fly
James Fly United States
7/28/2016 10:25:36 PM #

This is such a great site come check out our new free Dating web site would wide fined your true love at http://youllfindlove.com/

Reply

James Fly
James Fly United States
8/6/2016 9:13:03 AM #

This is such a great site come check out our new free dating website we are world wide find your true love at http://youllfindlove.com

Reply

Nadene Bridgens
Nadene Bridgens United States
8/8/2016 2:30:12 PM #

Hire a professional writer for just $5. Visit: http://bit.ly/29sFchi

Reply

Jamie Valvano
Jamie Valvano United States
8/8/2016 7:58:25 PM #

Hire a professional writer for just $5. Visit: http://bit.ly/29sFchi

Reply

Clyde Bialik
Clyde Bialik United States
8/25/2016 4:22:14 AM #

I stayed in Manila and would like to find a Smart Home Builders to do our home designs. An educational post about this subject would be very helpful.

Reply

Dusty Peroutka
Dusty Peroutka United States
8/26/2016 2:31:24 AM #

Hey there! Do you use Twitter? I'd like to follow you if that would be okay. I'm undoubtedly enjoying your blog and look forward to new posts.

Reply

Cayla Magin
Cayla Magin United States
9/3/2016 6:27:36 PM #

I am typically to blogging and i also actually appreciate your posts. The content has really peaks my interest. Let me bookmark your internet site and keep checking achievable details.

Reply

clash of clans hack gems illimit&#233;
clash of clans hack gems illimité United States
9/4/2016 11:12:59 PM #

nice and great posting i like it ! thanq you

Reply

Más de 21.000 docentes de ESO, Bachillerato y FP de la Comunidad de Madrid estaban llamados este martes a la primera de las dos jornadas de huelga convocadas por los sindicatos del sector FREM CCOO, FETE-UGT Madrid, STEM, ANPE Madrid y CSI-F Madrid. Nadie mejor que nosotros sabe que la convocatoria de una huelga general ha de responder a una situación excepcional. Tiene la rebeldía que le permite dibujar una escena fructífera en contraste con lo correcto.

Reply

Celena Weyer
Celena Weyer United States
10/13/2016 4:17:04 PM #

rachunki bankowe

Reply

Cody Bearded
Cody Bearded United States
10/13/2016 4:17:13 PM #

kredyt

Reply

Genaro Fierros
Genaro Fierros United States
10/13/2016 4:24:09 PM #

ekonto

Reply

Valentine Calvino
Valentine Calvino United States
10/13/2016 4:24:14 PM #

kredyt mbank

Reply

Ashton Sabi
Ashton Sabi United States
10/13/2016 4:24:28 PM #

kredyt konsolidacyjny

Reply

SZYBKA POŻYCZKA DO DOMU KLIENTA

Reply

UBEZPIECZENIA MAJĄTKOWE

Reply

POŻYCZKA HIPOTECZNA

Reply

Connie Sharlow
Connie Sharlow United States
10/17/2016 9:26:55 AM #

Empresa especializada en la venta de Electrodomésticos, Servicio Técnico de Reparación e Instalación de Electrodomésticos en la Comunidad de Madrid.  Es por eso que sólo contratamos técnicos licenciados que están capacitados y con experiencia en todas las reparaciones de electrodomésticos y no sólo para hacer bien el trabajo, si no también muy rápido! Nuestra máxima prioridad para minimizar las molestias de un electrodoméstico roto para conseguir ponerlo en funcionamiento en el menor tiempo posible.

Reply

Como Servicio Técnico Oficial Autorizado, ofrecemos la garantía de reparaciones y piezas establecidas por la ley. S.A.T Madrid Servicios es una empresa española especializada en reparación, venta de productos y accesorios-recambios, e instalación de electrodomésticos de gama blanca, calderas, termos, calentadores y aparatos de aire acondicionado y Frío Industrial. Hombre de 25 a 30 años de edad, con conocimiento en facturación, cobro, atención al cliente.

Reply

Julieta Rodeiguez
Julieta Rodeiguez United States
1/27/2017 12:12:26 PM #

POZYCJONOWANIE

Reply

Kermit Massaquoi
Kermit Massaquoi United States
1/27/2017 12:16:40 PM #

pozycjonowanie

Reply

Tuan Bolick
Tuan Bolick United States
1/27/2017 12:16:41 PM #

pozycjonowanie

Reply

Rudolph Plauche
Rudolph Plauche United States
1/27/2017 12:16:46 PM #

pozycjonowanie

Reply

Add comment

biuquote
  • Comment
  • Preview
Loading

Rel=Me

Month List

RecentComments

Comment RSS