如何检测.NET(执行线程关联)跨线程访问? [英] How to detect cross thread access in .NET (enforce thread affinity)?

查看:249
本文介绍了如何检测.NET(执行线程关联)跨线程访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个特殊的数据结构,将可在.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:

  • <一个href="http://blogs.msdn.com/jaredpar/archive/2008/02/22/thread-affinity.aspx">http://blogs.msdn.com/jaredpar/archive/2008/02/22/thread-affinity.aspx

这篇关于如何检测.NET(执行线程关联)跨线程访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆