Reputation: 3031
In my program I need to process files. My program could use several threads to process files and therefore I need some sort of locking, because each file should not be processed by more than one thread at a time.
private object lockObj = new object();
public void processFile(string file)
{
lock(lockObj)
{
//... actuall processing
}
}
With the above code only one file can be processed at a time, but two threads should be able to process two different files at a time, but not the same file.
My first idea was to create a Dictionary with the key beeing the file and the value beeing the lock-object. But I was wondering if it would also be possible to lock the string file? Any thoughts on this?
PS: sorry for not beeing able to find a better title
Upvotes: 3
Views: 316
Reputation: 13097
If you're working with threads in c#, you owe it to yourself to check out the task parallel library (TPL). There's a learning curve, but once you get the hang of it your multi-threaded code will be simpler and more maintainable.
Here's an example that does exactly what your asking using TPL.
Upvotes: 0
Reputation: 62459
I think you are approaching this the wrong way. You can simply use a producer-consumer pattern with a BlockingCollection. A thread keeps reading files and putting them in the queue (using Add
) and a bunch of worker threads keep taking from the queue (using Take
) and processing files. The way the queue is implemented it's guaranteed that two threads cannot retrieve the same file, so no explicit locking is needed.
Upvotes: 2
Reputation: 564771
My first idea was to create a Dictionary with the key beeing the file and the value beeing the lock-object. But I was wondering if it would also be possible to lock the string file? Any thoughts on this?
If the strings will be created at runtime, locking on the string will not be safe. It would be better to make a dictionary of objects, and use those to lock.
That being said, you should consider using a ConcurrentDictionary<string,object>
for this dictionary, as it will prevent a race condition (or other lock) in your dictionary itself. By using GetOrAdd you can safely get the appropriate object to use for locking.
That being said, a different approach may be appropriate here. You could use a ConcurrentQueue
or BlockingCollection
to provide a list of items to process, and then have a fixed number of threads process them. This will prevent synchronization problems from occurring in the first place.
Upvotes: 4