If this is the same process (note same EXE doesn't matter) then a lock would be fine since it is all in the same memory space. You also tagged this as ASP.NET which changes everything if this is actually a web app.
We already have concurrent structures that may help. Also note that SyncRoot
isn't really useful anymore and probably shouldn't be used. There is no benefit. It was a v1 threading solution but you gain nothing by using it.
If you have a producer-consumer situation where one or more threads add data to be processed and a single consumer that processes the data then a ConcurrentQueue might be a good starting solution. It already handles concurrency.
If you want to stick with a traditional List<T>
then you would need to lock the list when adding or reading. The general recommendation is to wrap this list management in a helper class. Inside the helper class, lock the list when working with it.
class WorkerQueue
{
public void Add ( MyData item )
{
lock(_items)
{
_items.Enqueue(item);
};
}
public MyData GetNext ()
{
lock(_items)
{
if (_items.Count > 0)
return _items.Dequeue();
return null;
};
}
private readonly Queue<MyData> _items = new Queue<MyData>();
}
Note that this is just reinventing what ConcurrentQueue
already does. Perhaps a better option is to have the processor manage the queue and the other process just adds work to it.
Also note that durability may be important. For example if something fails during processing of the work then the item has already been removed from the queue. Either that work would be lost or your worker process needs to recover and try again, report an error, etc.