如何检测.NET(执行线程关联)跨线程访问?线程、NET

由网友(梦醒人已散)分享简介:我正在写一个特殊的数据结构,将可在.NET库和这个数据结构的特点之一是将是线程安全的规定,只有一个线程将数据写入到它,只有一个线程从它(读线程和写线程可以不同)。I'm writing a special data structure that will be available in a .NET library...

我正在写一个特殊的数据结构,将可在.NET库和这个数据结构的特点之一是将是线程安全的规定,只有一个线程将数据写入到它,只有一个线程从它(读线程和写线程可以不同)。

I'm writing a special data structure that will be available in a .NET library and one of the features of this data structure is that is will be thread safe provided that only one thread writes data to it, and only one thread reads data from it (the reader thread and the writer thread can be different).

现在的问题是我怎么可以强制所有的读操作都是由同一个线程中执行?

The question is how can I enforce that all Read operations are executed by the same thread?

我的解决办法是捕捉System.Threading.Thread.ManagedThreadID并将其存储在在第一次读一个私有成员。然后,在随后的读取来检查ManagedThreadID对保存的之一,如果它们是不同的抛出异常。

My solution would be capture the System.Threading.Thread.ManagedThreadID and store it in a private member upon the first Read. Then, on subsequent reads to check the ManagedThreadID against the saved one and if they are different to throw an exception.

这就够了,还是有不同的更为可靠的机制来这样做。

Is that enough, or is there a different more reliable mechanism for doing this.

注:有一个要求,这个库是可用的没有Windows.Forms的背景下... 的

推荐答案

当我遇到这种情况我使用一类我编写的名为ThreadAffinity。它的全部目的是为了记录当前线程,并扔在从不同的线程无效的访问。您必须手动做检查,但它封装了你的工作​​量小。

When I run into this situation I use a class I wrote called ThreadAffinity. It's entire purpose is to record the current thread and throw on invalid accesses from a different thread. You have to manually do the check but it encapsulates the small amount of work for you.

class Foo {
  ThreadAffinity affinity = new ThreadAffinity();

  public string SomeProperty {
    get { affinity.Check(); return "Somevalue"; }
  }
}

[Immutable]
public sealed class ThreadAffinity
{
    private readonly int m_threadId;

    public ThreadAffinity()
    {
        m_threadId = Thread.CurrentThread.ManagedThreadId;
    }

    public void Check()
    {
        if (Thread.CurrentThread.ManagedThreadId != m_threadId)
        {
            var msg = String.Format(
                "Call to class with affinity to thread {0} detected from thread {1}.",
                m_threadId,
                Thread.CurrentThread.ManagedThreadId);
            throw new InvalidOperationException(msg);
        }
    }
}

关于这个问题的博客文章:

Blog post on the subject:

http://blogs.msdn.com/jaredpar/archive/2008/02/22/thread-affinity.aspx
阅读全文

相关推荐

最新文章