0

我有 JournalService 类,它收集事件的记录。该类在列表中收集记录。事件来自多个线程。记录列表长度有限制。我正在使用.NET 4.0。为了使其线程安全,我锁定了对“记录”列表的读写访问。我在这件事上没有经验,我不确定我做得很好。可能我必须使用System.Collections.Concurrent 命名空间

我的问题是:我是否需要修复我的代码以及要使用的并发类以及如何使用?

当前代码是:

public class JournalService : IJournalService
{
    private readonly List<JournalRecord> records = new List<JournalRecord>();
    private readonly ISettings settings;

    public JournalService(IEventAggregator eventAggregator, ISettings settings)
    {
        if (eventAggregator == null) throw new ArgumentNullException("eventAggregator");
        if (settings == null) throw new ArgumentNullException("settings");

        this.settings = settings;
        eventAggregator.JournalRecordPosted += EventAggregator_JournalRecordPosted;
    }

    public IEnumerable<JournalRecord> GetRecords()
    {
        JournalRecord[] tempRecords;
        lock (records)
        {
            tempRecords = records.ToArray();
        }
        return tempRecords;
    }

    private void EventAggregator_JournalRecordPosted(object sender, JournalRecordEventArgs e)
    {
        lock (records)
        {
            int surplus = records.Count - settings.TradeJournalLength;
            if (surplus == 0)
                records.RemoveAt(0);
            else if (surplus > 0)
                records.RemoveRange(0, surplus);
            records.Add(e.Record);
        }
    }
}

编辑:盈余计算放在锁内。 编辑:添加检查盈余 == 0

4

2 回答 2

0

使用并发队列:

private void EventAggregator_JournalRecordPosted(object sender, JournalRecordEventArgs e)
{
    records.Enqueue(e.Record);

    if (records.Count >= settings.TradeJournalLength)
    {
        recordType temp = null;
        records.TryDequeue(out temp);
    }
}
于 2013-10-18T17:34:36.437 回答
0

您可以使用无锁的 ConcurrentQueue

private int _length = 0;
private void EventAggregator_JournalRecordPosted(object sender, JournalRecordEventArgs e)
{
    records.Enqueue(e.Record);


    if(Interlocked.Increment(ref _length)>=settings.TradeJournalLength)
    while(!records.Dequeue())
    {

    }
Interlocked.Decrement(ref _length)
}
于 2013-10-18T16:49:32.813 回答