我的要求是这样的。我没有几个独立的工作,也没有几个遵守合同的顺序工作。在我的客户端应用程序中,在Parallel For循环中,我需要确保独立任务以任意顺序执行,但是如果它们是顺序的,它们应该是一个接一个。下面是我的代码。谢谢,并行执行每个循环的顺序执行
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 ");
}
}
}
欲出把
这是独立工作 第一步:从XML 获取数据第二步:转储数据whihc排在XML 这是独立工作 按任意键继续。 。 。
我可以这样做
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());
而你的问题? – 2012-03-07 18:31:12
我的问题是我如何确定如果步骤2只是在步骤1之后才到来,那么 – 2012-03-07 18:36:25