views:

153

answers:

3

I have a method that for thread-safety reasons should only ever be used by a particular thread. If another thread tries to use it, I would like an exception to be thrown.

public void UnsafeMethod()
{
    if (CurrentThreadId != this.initialThreadId)
        throw new SomeException("Can only be run on the special thread.");
    // continue ...
}

How can I find the CurrentThreadId in the code above? Or alternatively is there some other way of achieving what I want to do?

A: 

I guess you need something along the lines of a static variable (a global variable in disguise) to do this. It doesn't feel very good to me, but putting this method in a singleton object would let you have that.

Curt Sampson
+4  A: 

Thread.CurrentThread.ManagedThreadId

Or you could just store a reference to the thread object itself and compare that to Thread.CurrentThread.

Thanks very much. I did not see CurrentThread. I must be going blind.
dangph
+3  A: 

Name your thread at the time of creation

System.Threading.Thread thread = new System.Threading.Thread(..);
thread.Name = "MySpecialThread";

And check this condition where you want thread specific code:

if (System.Threading.Thread.CurrentThread.Name == "MySpecialThread")
{
    //..
}
Ramesh Soni
Excellent idea. The nice thing is that you don't have to store the thread id anywhere. Unfortunately though I can have more than one of these threads, so I would have to generate unique names for them (rather than just using a constant, if there were a single thread), which would makes things a bit less clear.
dangph