What exactly is the thread context in C#?
Asked Answered
T

1

8

I have a WCF service and it logs each call to the database. Later on, if an exception occurs, it is also logged to a separate database.

I wanted a way to tie both of these logs together so we can see what might have caused the exception. To do this, I wanted some kind of unique ID that I could get for each call.

Since the whole thing is executing on a single thread, I could for example, set the thread name to a GUID eg. System.Threading.Thread.CurrentThread.Name = Guid.NewGuid().ToString(); but this is a bit hacky.

Searching around the net, I discovered System.Threading.Thread.CurrentContext.SetProperty() but I am wondering exactly what that context is. Is it designed to store properties for the duration of a thread? Is it unique per thread?

If I have 5 simultaneous WCF calls I don't want there to be any conflicts between what's going in the context if it's not 'per call' so to speak.

Could someone clarify?

Teide answered 3/6, 2013 at 13:28 Comment(0)
C
7

I wouldn't use that property since Microsoft say it's for internal use only:

"This API supports the .NET Framework infrastructure and is not intended to be used directly from your code."

However, you should be able to use Thread Local Storage to do the same kind of thing. That link gives an example showing how to set a string property for a thread.

Also see http://www.c-sharpcorner.com/UploadFile/1d42da/working-with-thread-local-storagetls-in-C-Sharp/

Contrarily answered 3/6, 2013 at 13:41 Comment(1)
As a update, if you are using .NET 4.6 you should switch from using ThreadLocal to AsyncLocal, this allows your storage to flow across a async/await boundary where you could end up jumping threads.Merengue

© 2022 - 2024 — McMap. All rights reserved.