小编K.M*_*.M.的帖子

是否使用通用List线程是安全的

我有一个System.Collections.Generic.List<T>我只在计时器回调中添加项目.仅在操作完成后重新启动计时器.

我有一个System.Collections.Concurrent.ConcurrentQueue<T>存储上面列表中添加项目的索引.此存储操作也始终在上述相同的计时器回调中执行.

是一个读取操作,它迭代队列并访问列表线程中的相应项目安全吗?

示例代码:

private List<Object> items;
private ConcurrentQueue<int> queue;
private Timer timer;
private void callback(object state)
{
    int index = items.Count;
    items.Add(new object());
    if (true)//some condition here
        queue.Enqueue(index);
    timer.Change(TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(-1));
}

//This can be called from any thread
public IEnumerable<object> AccessItems()
{
    foreach (var index in queue)
    {
        yield return items[index];
    }
}
Run Code Online (Sandbox Code Playgroud)

我的理解:即使列表在索引时被调整大小,我只访问已经存在的项目,因此无论是从旧数组还是新数组中读取它都无关紧要.因此,这应该是线程安全的.

.net c# thread-safety

7
推荐指数
2
解决办法
1741
查看次数

标签 统计

.net ×1

c# ×1

thread-safety ×1