A task 完成后执行 B任务 ,B完成后再执行A 接着B 依次循环,我使用continuewith 还有while循环,会闪退 Console.ReadKey();不会停下来
class Program
{
static BlockingCollection<DataRow> bc = new BlockingCollection<DataRow>(new ConcurrentQueue<DataRow>(),1000);
static int count = 1000;
static void Main(string[] args)
{
DataTable table = new DataTable();
DataColumn co1 = new DataColumn("ID", typeof(string));
table.Columns.Add(co1);
Action InitTable = () => {
Console.WriteLine("InitTable");
for (int i = 0; i < count; i++)
{
DataRow row = table.NewRow();
row["ID"] = i.ToString();
table.Rows.Add(row);
bc.Add(row);
}
};
Action<Task> readrow = (Task task) =>
{
Console.WriteLine("readrow");
if (task.IsFaulted)
{
Console.WriteLine("error");
}
else
{
Parallel.For(0, count, (i) =>
{
ww(table.Rows[i]);
});
Console.WriteLine("收尾任务!");
Console.ReadKey();
}
};
Task task1 = new Task(InitTable);
task1.ContinueWith(readrow);
task1.Start();
}
static void ww(DataRow row)
{
Console.WriteLine("tb"+row["ID"].ToString());
}
}
改成如下这样:
Task task1 = new Task(InitTable); var task2 = task1.ContinueWith(readrow); task1.Start(); task2.Wait();
task2并不会等待你的readrow执行完