简体   繁体   English

多个线程之间共享的枚举

[英]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: 在一个类中,我有一个Action类型的变量:

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#? 如何在C#中将InterLocked.Exchange应用于枚举类型?

Problem here is that enumeration needs to cast to an int, but I would like to keep enumeration without casting. 这里的问题是枚举需要强制转换为int,但我想保留枚举而不强制转换。 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. 我的意思是对可变枚举应用互锁。

In this scenario Interlocked wouldn't be useful. 在这种情况下, Interlocked将不会有用。 Your series of if/then checks depend on the value of _action remaining unchanged as they all execute. 您的一系列if/then检查取决于_action的值在它们全部执行时保持不变。 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. 否则_action==Action.Read可能为false,但是在下_action语句执行之前, _action设置为Action.Read ,其他所有条件均为false。

You'd want to use lock to ensure that nothing modifies _action while those statements are executing. 您希望使用lock来确保在执行这些语句时没有任何动作可以修改_action

So you might have an object for your lock: 因此,您可能有一个锁对象:

private readonly _lockObject = new object();

And then when _action is getting set: 然后在设置_action时:

lock(_lockObject)
{
    _action = newValue;
}

And when executing your conditions you could just read the value of _action within the lock and then release it. 执行条件时,您可以只读取lock_action的值,然后释放它。 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的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM