Yaron
Yaron

Reputation: 233

Threads design when need both: wait and continue

.Hi, I need to run every task T in the Tasklist in different thread, and when every T finish, do something Without bothering the main program or anther threads. [And I cann't change the myTask.runTask() method ]

Can you suggest me the correct design to do it?

foreach (myTask T in this.TaskList)
{
    if (T.NextRunTime<=Now);
        new Thread(() => T.runTask()).Start(); //When done: Do 'something'...
        //do more stuff                   
}

Thanks

Upvotes: 0

Views: 77

Answers (4)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13774

try this

class Program
  {
   static List<Task>  allTasks = new List<Task>();
    static void Main(string[] args)
    {
        foreach (myTask T in this.TaskList)
            {
       if (T.NextRunTime<=Now);
               var task=  Task.Factory.StartNew(() => T.runTask().Start());
                 task.ContinueWith( delegate
                                              {
                                                  //code  for your continuation 
                                                  //you can call the method for doing this  
                                              },TaskContinuationOptions.NotOnFaulted);

                 try
                 { // and here to handle all  your exceptions  
                     task.Wait();

                 }
                 catch (AggregateException ae)
                 {

                     ae.Handle((x) =>
                     {

                         return true;
                     });

                 }
            }
        //you can even try someting  like this  
        // Task.WaitAll(allTasks.ToArray());  
    }
}

Upvotes: 1

Servy
Servy

Reputation: 203843

Just start a new Task for each task that you want to run and then use WhenAll to execute code when they have all run.

var tasks = TaskList.Where(task => task.NextRunTime <= Now)
    .Select(task => Task.Run(() => task.runTask()));

task.WhenAll(tasks)
    .ContinueWith(t => {
        //do stuff
    });

Upvotes: 1

Moho
Moho

Reputation: 16553

Use Task with a call to .ContinueWith(...) to specify code to execute upon completion of the task's execution

        foreach (myTask T in this.TaskList)
        {
            if (T.NextRunTime<=Now)
            {
                var task = new Task( T.runTask() );
                task.ContinueWith( <Action to execute on task completion> );
                task.Start();
            }                 
        }

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46008

var threads = this.TaskList
    .Where(t => t.NextRunTime <= Now)
    .Select(t => new Thread(() => { t.runTask(); /* Do 'something' */ }))
    .ToList();

threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
//do more stuff (all threads finished)

Upvotes: -1

Related Questions