0

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.

RagtimeWilly
  • 5,265
  • 3
  • 25
  • 41

2 Answers2

1

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

Learner
  • 1,490
  • 2
  • 22
  • 35
  • and if that wont do for u try something else from the parallel lib, it was created exactly for us programmers to stop using all kind of combinations like sleep – bresleveloper Jul 11 '12 at 10:42
  • Sorry, I should have mentioned that the application is already threaded. So that's not the issue. I was looking looking for something more like 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. – RagtimeWilly Jul 11 '12 at 12:01
0

If you want Asynchronous Call , You can use Task.Factory.Startnew() else go with Parallel.ForEach() . Hope this will help .. here and here

Community
  • 1
  • 1
C-va
  • 2,910
  • 4
  • 27
  • 42