C#中的挥发性数组项? [英] C# volatile array items?

查看:140
本文介绍了C#中的挥发性数组项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的挥发性元素的数组,并不能找到一个方法来做到这一点。

 私人挥发性T [] _​​arr;
 

这意味着该_arr参考是挥发性的,但它并不能保证有关_arr对象本身内部的物品的任何

有没有什么办法,以纪念_arr的项目为挥发性?

感谢。

编辑:

按二进制codeR的回答内置下面code。 这是code线程安全使用?

 公共类VolatileArray< T>
{
    私人T [] _​​arr;

    公共VolatileArray(INT长度)
    {
        _arr =新T [长度];
    }

    公共VolatileArray(T [] ARR)
    {
        _arr = ARR;
    }

    公共牛逼这个[INT指数]
    {
        得到
        {
            t值= _arr [指数]
            Thread.MemoryBarrier();
            返回值;
        }

        组
        {
            Thread.MemoryBarrier();
            _arr [指数] =值;
        }
    }

    公众诠释长度
    {
        {返回_arr.Length; }
    }
}
 

解决方案

由于可以通过引用传递数组元素,你可以使用 Thread.VolatileRead Thread.VolatileWrite

要明白,挥发性关键字用在幕后工作 Thread.MemoryBarrier 这是非常有用的。你可以写:

  //读取
X = _arr [I];
Thread.MemoryBarrier();

// 写
Thread.MemoryBarrier();
_arr [I] = X;
 

注意挥发性 MemoryBarrier 是先进的技术,既容易出错。例如,看到<一href="http://stackoverflow.com/questions/1787450/how-do-i-understand-read-memory-barriers-and-volatile">http://stackoverflow.com/questions/1787450/how-do-i-understand-read-memory-barriers-and-volatile.通常,你最好采用更高级别的结构,如锁定显示器 ReaderWriterLockSlim ,和其他人。

I need an array with volatile items, and can't find a way to do that.

private volatile T[] _arr;

This means that the _arr reference is volatile, however it does not guarantee anything about the items inside the _arr object itself.

Is there any way to mark the _arr's Items as volatile?

Thanks.

EDIT:

The following code built according to binarycoder's answer. Is this code thread-safe to use?

public class VolatileArray<T>
{
    private T[] _arr;

    public VolatileArray(int length)
    {
        _arr = new T[length];
    }

    public VolatileArray(T[] arr)
    {
        _arr = arr;
    }

    public T this[int index]
    {
        get
        {
            T value = _arr[index];
            Thread.MemoryBarrier();
            return value;
        }

        set
        {
            Thread.MemoryBarrier();
            _arr[index] = value;
        }
    }

    public int Length
    {
        get { return _arr.Length; }
    }
}

解决方案

Since it is possible to pass array elements by reference, you can use Thread.VolatileRead and Thread.VolatileWrite.

It is useful to understand that the volatile keyword works behind the scenes by using Thread.MemoryBarrier. You could write:

// Read
x = _arr[i];
Thread.MemoryBarrier();

// Write
Thread.MemoryBarrier();
_arr[i] = x;

Note that volatile and MemoryBarrier are advanced techniques that are both easy to get wrong. For example, see http://stackoverflow.com/questions/1787450/how-do-i-understand-read-memory-barriers-and-volatile. Usually you are better off with higher level constructs such as lock, Monitor, ReaderWriterLockSlim, and others.

这篇关于C#中的挥发性数组项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆