线程设计何时需要:等待和继续

时间:2013-11-27 15:16:40

标签: c# multithreading

.Hi,我需要在T的不同线程中运行每个任务Tasklist,当每个T完成时,执行something而不用打扰主程序或其他线程。 [我不能改变myTask.runTask()方法]

你能建议我做正确的设计吗?

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

由于

4 个答案:

答案 0 :(得分:1)

使用Task调用.ContinueWith(...)来指定在完成任务执行时要执行的代码

        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();
            }                 
        }

答案 1 :(得分:1)

为每个要运行的任务启动一个新Task,然后使用WhenAll在所有代码运行时执行代码。

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

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

答案 2 :(得分:1)

试试这个

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());  
    }
}

答案 3 :(得分:-1)

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)