Salvatore Sorbello
Salvatore Sorbello

Reputation: 606

Implement a cross-thread call check

I need to check that a method is called from the same thread that instantiated the class similar to the feature implemented by a WinForms Control.

How can achieve this? is the following example valid?

public class Foo
{
  int ManagedThreadId; 
  public Foo()
  {
    ManagedThreadId=Thread.CurrentThread.ManagedThreadId;
  }

  public void FooMethod()
  {
    if (ManagedThreadId!=Thread.CurrentThread.ManagedThreadId)
        throw new InvalidOperationException("Foo accessed  from a thread other than the thread it was created on.");

    //Method code here.
  }
}

Im not so sure that storing the ManagedThreadId is enough to achieve this. If i store a reference to the Thread, can this create problems to the GC or to something else?

Upvotes: 4

Views: 76

Answers (1)

andyp
andyp

Reputation: 6269

The ManagedThreadId should be fine for this task, the MSDN documentation for Thread states that it doesn't vary over time.

After looking at the reference source for the WPF window verifies its not used across threads, I think it is also okay to keep a reference to the Thread your class is instantiated on, as that's what it does: storing a Dispatcher which in turn keeps a reference to its Thread.

Upvotes: 4

Related Questions