Anton
Anton

Reputation: 1515

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

Basically, I'm curious if there is something that would make the following happen.

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
}

Regards, Anton

Upvotes: 3

Views: 98

Answers (1)

Douglas
Douglas

Reputation: 54877

From your example, I assume you need to implement a method that can only be executed on a single designated thread. To achieve this, you could use a thread-static field to identify the designated thread – for example, by setting a flag from the constructor.

class MyClass
{
    [ThreadStatic]
    bool isInitialThread;

    public MyClass()
    {
        isInitialThread = true;
    }

    public void MyMethod() { }

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

Don't use ManagedThreadId for this purpose – see Managed Thread Ids – Unique Id’s that aren’t Unique.

Upvotes: 3

Related Questions