Reputation: 5445
I have a program that is monitoring for changes in files and then processing updates when a change arises.
I need to be able to process changes on different files concurrently, but can only process changes in the same file sequentially.
Each file has a unique id so currently I am using a ConcurrentDictionary to monitor which tasks are currently processing and blocking until the second update can be processed:
private ConcurrentDictionary<int, ITask> activeTasks =
new ConcurrentDictionary<int, ITask>();
public bool TryProcessTask(ITask task)
{
while(activeTasks.ContainsKey(task.Id))
{
Thread.Sleep(50);
}
activeTasks.TryAdd(task.Id, task);
bool isProcessed = task.TryProcess();
ITask t;
activeTasks.TryRemove(task.Id, out t);
return isProcessed;
}
I was wondering if someone would be able to tell me a better way to do this?
I would have assumed there would be a specific .NET object which would cater to this scenario?
Thanks,
EDIT
To clarify, I'm looking looking for something similar to a queue that I can pass items to and if there is no other items with the same id it will process, otherwise it will block until the existing process with the same id is finished.
Upvotes: 0
Views: 369
Reputation: 2910
If you want Asynchronous Call , You can use Task.Factory.Startnew() else go with Parallel.ForEach() . Hope this will help .. here and here
Upvotes: 0
Reputation: 1542
Use Task parallel library..
Task.Factory.StartNew(METHOD).ContinueWith(task => DispatcherHelper.Dispatch(() => { Mouse.OverrideCursor = null; }));
It will first complete the first task and then only start the new task using continuewith
Upvotes: 1