Răspuns multithread - waiting for threads

  • 13 martie 2012 18:27
     
      Are cod

    I've used the background worker a few times, but haven't really worked with multithreading.

    I have a program that reads in 3 files, each to a table, then validates the data in each table before working with all 3 tables together.  The validation takes a long time, so I'd like each table to validate its data at the same time.  Once the validation is done the program can continue in a single thread to work with the 3 tables together.

    Here's a sample of what my method looks like.

    public void FixData(string File1, string File2, string File3)
    {
       DataTable dt1 = CreateTableFromFile(File1);
       DataTable dt2 = CreateTableFromFile(File2);
       DataTable dt3 = CreateTableFromFile(File3);
    
       //run these 3 in seperate threads
       ValidateData(dt1);
       ValidateData(dt2);
       ValidateData(dt3);
       
       //once the validation threads are done continue
       DataTable dtPrintable = CombineData(dt1, dt2, dt3);
       
       OutputData(dtPrintable);
    }

    Thanks in advance,

    Scott

Toate mesajele

  • 13 martie 2012 18:38
     
      Are cod

    Do it this way:

            public void FixData(string File1, string File2, string File3)
            {
                DataTable dt1 = CreateTableFromFile(File1);
                DataTable dt2 = CreateTableFromFile(File2);
                DataTable dt3 = CreateTableFromFile(File3);
    
                //run these 3 in seperate threads
                new Thread(new ParameterizedThreadStart(ValidateData)).Start(dt1);
                new Thread(new ParameterizedThreadStart(ValidateData)).Start(dt2);
                new Thread(new ParameterizedThreadStart(ValidateData)).Start(dt3);
    
                //once the validation threads are done continue
                //DataTable dtPrintable = CombineData(dt1, dt2, dt3);
                //OutputData(dtPrintable);
            }
    
            private DataTable CreateTableFromFile(string file)
            {
                DataTable table = new DataTable();
                //creating table..
                return table;
            }
    
            private void ValidateData(object obj)
            {
                DataTable table = (DataTable)obj;
                //do your work here...
            }


    Mitja

  • 13 martie 2012 18:44
     
     Răspuns
    You'll want to store the Thread returned from 'new Thread' and call join on all three of them after starting all three.  Join() will block until that thread is done executing.
    • Marcat ca răspuns de Scott_P 13 martie 2012 20:05
    •