dan-gph
dan-gph

Reputation: 16909

How to restrict a method to a particular thread?

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?

Upvotes: 2

Views: 302

Answers (3)

Ramesh Soni
Ramesh Soni

Reputation: 16077

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")
{
    //..
}

Upvotes: 4

David Nelson
David Nelson

Reputation: 3714

Thread.CurrentThread.ManagedThreadId

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

Upvotes: 5

cjs
cjs

Reputation: 27221

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.

Upvotes: 0

Related Questions