是否有任何等效于使用 C# 限制对一个线程的访问的访问修饰符?

Is there anything equivalent to an access modifier that limits access to only one thread using C#?

基本上,我很好奇是否有什么东西会导致以下情况发生。

class MyClass
{
    public void MyMethod() { }

    public void MyNonThreadMethod() { }
}

public void OtherThread(MyClass myObject)
{
    Thread thread = new Thread(myObject.MyMethod);
    thread.Start(); // works

    thread = new Thread(myObject.MyNonThreadMethod);
    thread.Start(); // does not work
}

此致,安东

根据您的示例,我假设您需要实现一个只能在单个指定线程上执行的方法。为此,您可以使用线程静态字段来标识指定的线程——例如,通过在构造函数中设置标志。

class MyClass
{
    [ThreadStatic]
    bool isInitialThread;

    public MyClass()
    {
        isInitialThread = true;
    }

    public void MyMethod() { }

    public void MyNonThreadMethod() 
    {
        if (!isInitialThread)
            throw new InvalidOperationException("Cross-thread exception.");
    }
}

不要为此目的使用 ManagedThreadId – 参见 Managed Thread Ids – Unique Id’s that aren’t Unique