My requirement is some thing like this. I have few independent jobs and few sequential jobs which abide to a contract. In my client app, inside Parallel For loop I need to make to sure the independent tasks get executed in any order but if they sequential they should be one after another. below is my code. Thanks,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
List<IContract> list = p.Run();
Parallel.ForEach(list, t=> t.Execute());
}
List<IContract> Run()
{
List<IContract> list = new List<IContract>();
Type[] typesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes();
Array.ForEach(
typesInThisAssembly,
type =>
{
// If the type of this interface is not IChartView, continue the loop
if (type.GetInterface(typeof(IContract).ToString()) != null)
{
var contractObj = Activator.CreateInstance(type, new object[] { }) as IContract;
list.Add(contractObj);
}
});
return list;
}
}
public interface IContract
{
void Execute();
}
public class XMLJob : IContract
{
public void Execute()
{
Console.WriteLine("Step1: Getting data from XML");
}
}
public class DumpToDBJob : IContract
{
public void Execute()
{
Console.WriteLine("Step2: Dumping Data whihc came in XML");
}
}
public class IndependentJob1 : IContract
{
public void Execute()
{
Console.WriteLine("This is independent Job");
}
}
public class IndependentJob2 : IContract
{
public void Execute()
{
Console.WriteLine("This is independent Job ");
}
}
}
Desire Out Put
This is independent Job Step1: Getting data from XML Step2: Dumping Data whihc came in XML This is independent Job Press any key to continue . . .
Can I do like this
Program p = new Program();
List<IContract> list = p.Run();
IContract xj = list.Find(i => i.GetType().ToString() == typeof(XMLJob).ToString());
IContract dj = list.Find(i => i.GetType().ToString() == typeof(DumpToDBJob).ToString());
list.Remove(xj);
list.Remove(dj);
Parallel.ForEach(list, l => l.Execute());
List<Task> tasks = new List<Task>();
Task t1 = Task.Factory.StartNew(xj.Execute);
Task t2 = t1.ContinueWith((antecedent)=>dj.Execute());
tasks.Add(t1);
tasks.Add(t2);
Task.WaitAll(tasks.ToArray());