none
Thread-safety of a singleton class RRS feed

  • Question

  • Quick question for you threading/asynchronous experts: I have a static singleton class (it handles DB transactions for the entire application) that is not currently thread-safe. To make it so, thread-dependent members of the class such as the connections and parameter lists must be stored seperately by thread; I was thinking of using a generic Dictionary using the thread ID as key, and I'll also have to put lock blocks in each method so the reference to the thread won't change halfway through.

    My question is, when members of a static class are called from outside the main application thread, can the static class use Thread.CurrentThread.ManagedThreadId to determine the calling thread? I'm assuming it's the first case, but as I've only dealt with references to instantiated objects I don't know how a static class behaves in this scenario. If it works the way I think it does, no changes outside this object will be necessary.




    • Edited by Liko81 Thursday, July 31, 2008 9:55 PM adding a little detail
    Thursday, July 31, 2008 9:48 PM

Answers

  • The ThreadStaticAttribute was designed for that.  "Thread Local Storage" (TLS) in the Win32 API vernacular.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Wednesday, August 6, 2008 12:14 PM
    Friday, August 1, 2008 12:15 AM
    Moderator