Willy
Willy

Reputation: 10646

Shared enum between multiple threads

I have an enumeration that is shared between multiple threads:

public enum Action
{
   Read,
   Write,
   None
}

Within a class I have a variable of Action type:

public Action _action;

This is a shared variable, that is, it is updated and read from multiple threads.

For example, from one thread I do:

_action = Action.Read

And from another one:

if (_action == Action.Read)
{
}
else if (_action == Action.Write)
{
}
else if (_Action == Action.None)
{
}
else
{
}

So I would like to use Interlock to update and/or read it from different threads at the same time. How can I do it through a property?

I have seen many posts, for example below one:

How to apply InterLocked.Exchange for Enum Types in C#?

Problem here is that enumeration needs to cast to an int, but I would like to keep enumeration without casting. Is it possible? If so, could you post some example? Also Is it possible to combine volatile with interlock? I mean apply interlock on a volatile enumeration.

Upvotes: 0

Views: 1598

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29222

In this scenario Interlocked wouldn't be useful. Your series of if/then checks depend on the value of _action remaining unchanged as they all execute. Otherwise _action==Action.Read could be false, but before the next statement executes _action is set to Action.Read and all of the other conditions are false.

You'd want to use lock to ensure that nothing modifies _action while those statements are executing.

So you might have an object for your lock:

private readonly _lockObject = new object();

And then when _action is getting set:

lock(_lockObject)
{
    _action = newValue;
}

And when executing your conditions you could just read the value of _action within the lock and then release it. That way the lock is held for the shortest time possible. If _action gets modified while you're executing your conditions you won't be affected because you've created a separate value and you're no longer depending on the value of _action.

Action action;
lock(_lockObject)
{
    action = _action
}
if (action == Action.Read)
{
}
else if (action == Action.Write)
{
}
else if (action == Action.None)
{
}
else
{
}

Upvotes: 2

Related Questions