I need to write the actual user thread ID to a log file. If I use Thread.CurrentThread.ManagedThreadId I don’t get the unique ID, but the same one over and over again.
The reason is to track log.Info for user across the system, and later if I see a problem, I’ll be able to search in the log WHERE threadId = ? and get the entire activity flow from the log.
I don’t mind getting it inside the code of log4net.
I am talking about the server thread and not manual thread.
That is NOT possible because your threads in ASP.NET/IIS are running on the thread pool of IIS… it is not even guaranteed that a HTTP request runs completely on the same thread (for example if there is some I/O operation it could “go sleep” and get reassigned to another thread from the pool)…
What exactly is the goal ? Perhaps there is some other way to achieve that…
EDIT – as per comments:
To track a request you could try logging the hash code of that request (accessible via
GetHashCode()) and/or log a hash of a combination of the values of some of the properties/fields of the http request object…IF you dig deeper you could get your hands on a worker request object which has a (request specific)
TraceIDproperty…if you want to track the session that entirely depends on your session management (be it a hidden html form field and/or a cookie and/or user and/or something else…).