开发者

Get the unique thread ID

开发者 https://www.devze.com 2023-04-07 15:41 出处:网络
I need to write the actual user thread ID to a log file. If I use 开发者_JAVA百科Thread.CurrentThread.ManagedThreadId I don\'t get the unique ID, but the same one over and over again.

I need to write the actual user thread ID to a log file. If I use 开发者_JAVA百科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) TraceID property...

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...).


Your original assumption is inaccurate: the "actual thread" is reused again and again, which is why you're getting the same thread ID again and again.

Your mistake is to assume that each request will be handled by a separate thread. ManagedThreadId is working fine.

Now let's look at what you're trying to do:

The reason is to track log.Info for user across the system

So you want to track the interactions with a user. Not a thread, a user. The same user may have interactions on multiple threads, and multiple users may use the same thread... so what you want to log is the user ID, not the thread ID.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号