【发布时间】:2011-10-10 22:07:26
【问题描述】:
我有一个我正在跟踪的对象的动态列表,并且将来可能会使用许多线程。有人可以看看这个实现是否有错误吗?
换句话说,我想跟踪这个对象的许多实例:
object AzureBatchTrackerLock = new object();
Dictionary<string, List<TableServiceEntity>> AzureBatchTracker = new Dictionary<string, List<TableServiceEntity>>();
我目前的方法是使用 lock 和专用对象,以及 List 和 Dictionry 来处理动态数组...
BatchThread.cs
/// This object itself contains a dictionary AND a lock.
/// This object will ALSO be contained in a second dictionary that also has its own lock
public class BatchThread
{
// When I perform updates to AzureBatchTracker dictionary, lock the following
internal readonly object AzureBatchTrackerLock = new object();
internal Dictionary<string, List<TableServiceEntity>> AzureBatchTracker = new Dictionary<string, List<TableServiceEntity>>();
}
BatchProcessor.cs
public class BatchProcessor
{
// Class-wide scope
readonly object _BatchEntriesLock = new object();
Dictionary<string, BatchThread> _BatchEntries = new Dictionary<string, BatchThread>();
// The "outer loop"
public BatchThread GetAnEntry(string ThingToProcess)
{
// Prepare return variable
BatchThread foundBatchThread = null;
// And then I would select an object like this:
// Notice that I'm performing what may be a concurrent entry here
// on a non-locked object ............................
// Is this a bad idea? Should I lock? Does it matter?
// If I must lock, want to exit as quickly as possible. Must not be later than the next lock() command
var activeRow = _BatchEntries[ThingToProcess];
// Since I have the object I care about, I'll work with the "secondary" lock object
// It works in practice, but I don't know what kind concurrency issues I'll run into.
lock (activeRow.Value.AzureBatchTrackerLock)
{
// Add and remove from the collection
ActiveRow.Value.AzureBatchTracker.Add(new exampleEntry);
// Do Stuff
ActiveRow.Value.AzureBatchTracker.Remove(something);
foundBatchThread = activeRow.Value.AzureBatchTracker[ThingToProcess];
}
return foundBatchThread;
}
// The inner loop
// Called whenever the "Outer" array needs to be expanded
public void AddNewBatchEntry(string newEntryName)
{
lock (_BatchEntriesLock)
{
// Add placeholder to the collection
_BatchEntries.Add( newEntryName, new BatchThread() );
// Do Stuff
}
}
}
您在此实现中发现任何缺陷吗?有没有更好的办法?
【问题讨论】:
标签: c# multithreading concurrency dictionary locking