实现跨线程调用检查

实现跨线程调用检查

本文介绍了实现跨线程调用检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个方法是否从实例化类的同一线程调用,类似于 WinForms 控件实现的功能.

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

我不太确定存储 ManagedThreadId 是否足以实现这一点.如果我存储对 Thread 的引用,这会不会对 GC 或其他问题造成问题?

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?

推荐答案

ManagedThreadId 应该适合这个任务,MSDN Thread 文档指出它没有随时间变化.

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

查看 WPF 窗口的参考源后 验证它没有跨线程使用,我认为保留对您的类实例化的 Thread 的引用也是可以的,因为它是 它的作用:存储一个Dispatcher反过来,它会保留对其 Thread 的引用.

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.

这篇关于实现跨线程调用检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:01