Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有任何等效于使用C#限制对一个线程的访问的访问修饰符?_C#_.net_Multithreading_Access Modifiers - Fatal编程技术网

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

是否有任何等效于使用C#限制对一个线程的访问的访问修饰符?,c#,.net,multithreading,access-modifiers,C#,.net,Multithreading,Access Modifiers,基本上,我很好奇是否有什么东西会让下面的事情发生 class MyClass { public void MyMethod() { } public void MyNonThreadMethod() { } } public void OtherThread(MyClass myObject) { Thread thread = new Thread(myObject.MyMethod); thread.Start(); // works threa

基本上,我很好奇是否有什么东西会让下面的事情发生

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
}

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

class MyClass
{
    [ThreadStatic]
    bool isInitialThread;

    public MyClass()
    {
        isInitialThread = true;
    }

    public void MyMethod() { }

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

不要为此使用
ManagedThreadId
–请参阅。

[MethodImpl(methodimpoptions.Synchronized)]
您可以使用waitone之类的信号量: