0

I have a few thousand directories that I want to process concurrently. Unfortunately I have little to no experience in MultiThreading in C#.

I have:

A logger class implementing the observer pattern, notifying my form when a LogMessage was added within a Service. A form with a listView, getting notified when a Message was logged, that should add the Message to the listView A Service to which I handed over the Log Object

public partial class BrowseFolderForm : Form, ILogObserver
{    
    private IndexerService indexerService;
    private MessageLogger log;
    private static object syncLock = new object();


    public BrowseFolderForm(){
        log = new MessageLogger(this);
        indexerService = new IndexerService(log);
    }

    // Implementation of the logger classes observer callback interface
    public void NotifyChanges(Logger.Message m){
        lock (syncLock)
        {
            // add message m to the UltraListViewItem 
        }
    }

    public void startIndexing(){
       using (var finished = new CountdownEvent(1))
       {
           foreach (ObservedDirectory obsDir in dirs)
           {
              var capture = obsDir; 
              finished.AddCount();
              ThreadPool.QueueUserWorkItem(
              (state) =>
                 {
                    try
                    {
                        indexerService.StartIndexingModels(capture);
                    }
                   finally
                   {
                      //prgURLIndexing.Value = i++;
                      finished.Signal(); // Signal that the work item is complete.
                    }
                }, null);
           }
          finished.Signal(); // Signal that queueing is complete.
          finished.Wait(); // Wait for all work items to complete.
          MessageBox.Show("The task finished successfully.");
      }
   }   
}

The Problem is, inside the NotifyChanges method, I still get an error that the Control cannot be Access from another thread. What should I do?

spender
  • 117,338
  • 33
  • 229
  • 351
netik
  • 1,736
  • 4
  • 22
  • 45
  • In the NotifyChanges method, you need to use Control.Invoke as described in the duplicate that I'm about to close this for – spender Oct 15 '14 at 08:51
  • I'll bet if you search StackOverflow and/or the rest of the web on the exact text of the exception that's thrown, you'll get a plethora of useful advice, including the post that @spender is referencing as they close the thread as a dupe. – Peter Duniho Oct 15 '14 at 08:54

0 Answers0