多个线程之间共享的枚举 [英] Shared enum between multiple threads
问题描述
我有一个在多个线程之间共享的枚举:
I have an enumeration that is shared between multiple threads:
public enum Action
{
Read,
Write,
None
}
在一个类中,我有一个Action类型的变量:
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
还有另一个:
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:
如何为枚举类型应用InterLocked.Exchange在C#中?
How to apply InterLocked.Exchange for Enum Types in C#?
这里的问题是枚举需要强制转换为int,但我想保留枚举而不强制转换.是否有可能?如果是这样,您能发表一些例子吗?还有可能将挥发物与联锁结合起来吗?我的意思是对易失性枚举应用互锁.
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.
推荐答案
在这种情况下,Interlocked
不会有用.您的if/then
检查系列取决于_action
的值,因为它们都执行时保持不变.否则,_action==Action.Read
可能为false,但是在下一条语句执行之前,_action
设置为Action.Read
,其他所有条件均为false.
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.
您希望使用lock
来确保在执行这些语句时没有任何内容修改_action
.
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();
然后设置_action时:
And then when _action is getting set:
lock(_lockObject)
{
_action = newValue;
}
执行条件时,您可以只读取lock
中的_action
值,然后释放它.这样一来,锁就可以保持在最短的时间内.如果在执行条件时修改了_action
,则不会受到影响,因为您创建了一个单独的值,并且不再依赖于_action
的值.
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
{
}
这篇关于多个线程之间共享的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!