Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the thread context in C#?

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?

like image 487
NibblyPig Avatar asked Jun 03 '13 13:06

NibblyPig


People also ask

What is thread context in C?

The thread context includes all the information the thread needs to seamlessly resume execution, including the thread's set of CPU registers and stack. Multiple threads can run in the context of a process. All threads of a process share its virtual address space.

Why Context switching is faster in threads?

Context switches between threads are faster than between processes. That is, it's quicker for the OS to stop one thread and start running another than do the same with two processes. A context switch between processes is heavy.

How does a thread switch work?

Thread Switching : Thread switching is a type of context switching from one thread to another thread in the same process. Thread switching is very efficient and much cheaper because it involves switching out only identities and resources such as the program counter, registers and stack pointers.

What is thread context in Java?

The ThreadContext allows applications to store information either in a Map or a Stack. The MDC is managed on a per thread basis. To enable automatic inheritance of copies of the MDC to newly created threads, enable the "isThreadContextMapInheritable" Log4j system property.


1 Answers

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/

like image 79
Matthew Watson Avatar answered Oct 19 '22 17:10

Matthew Watson