使用迭代器访问并发队列是否安全? [英] Is it safe to access a concurrentqueue using an iterator?

查看:52
本文介绍了使用迭代器访问并发队列是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内存'循环'记录器,内部使用 ConcurrentQueue



发生错误,我访问内存中日志的内容,为错误消息提供额外的上下文。这一切似乎都运行正常。



然后我再次看了一下代码并开始怀疑我写的是否实际上是安全的,因为任何线程的事实理论上可以在访问日志内容的同时继续写入日志。



我的代码的基础知识如下:



I have an in-memory 'circular' logger that uses a ConcurrentQueue internally.

When an error occurs, I access the contents of the in-memory log to give additional context to the error message. It all seems to work fine.

Then I looked again at the code and began to wonder if what I had written was in fact safe, given the fact that any thread can theoretically continue to write to the log while the contents of the log are being accessed.

The basics of my code are as follows:

public class Logger
{
    public void WriteLine( string text )
    {
		_textLines.Enqueue( text );
		if( _textLines.Count > _MaxLines )
			_textLines.TryDequeue( out string discardable );
    }

    public string[] WholeLog { get { return _textLines.ToArray(); } }

	private ConcurrentQueue<string> _textLines = new ConcurrentQueue<string>();

    private const uint _MaxLines = 100;
}


public class SomeClientCode
{
    public void PrintOutContentsOfMemoryLog
    {
        foreach( string logLine in _logger.WholeLog )
            Debug.Write( logLine );
    }

    private Logger _logger = new Logger();
}



看起来这可能会导致问题吗?



什么我试过了:



我可以将内存中日志的大小增加到一个大数字,然后启动另一个线程并做一些写在第一个线程尝试打印日志的时候紧张的循环,但是我还没有完成这个测试,主要是因为我首先想从比我更好的程序员那里得到一个完整性检查。



我也知道,如果我对此有一个基本的误解,那么上面的测试可能不一定会出现问题。我想我说的真的是我想学点东西。


Does this look like it might cause a problem?

What I have tried:

I could increase the size of the in-memory log to a big number and then fire-up another thread and do some writing in a tight loop while the first thread attempts to print out the log, but I haven't done this test yet, mainly because I'd first like to get a sanity-check from better programmers than I.

I'm also aware that a test such as the one above might not necessarily show up a problem if I have a fundamental misunderstanding of this. I guess what I am saying really is that I'd like to learn something.

推荐答案

他们隐藏文档 [ ^ ]:

They hide information like that in the documentation[^]:
Quote:

枚举表示队列内容的时刻快照。调用GetEnumerator后,它不会反映对集合的任何更新。枚举器可以安全地与队列读取和写入同时使用。



枚举器按照添加顺序返回集合元素,即FIFO订单(先进先出)。

The enumeration represents a moment-in-time snapshot of the contents of the queue. It does not reflect any updates to the collection after GetEnumerator was called. The enumerator is safe to use concurrently with reads from and writes to the queue.

The enumerator returns the collection elements in the order in which they were added, which is FIFO order (first-in, first-out).


这篇关于使用迭代器访问并发队列是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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