【发布时间】:2017-10-05 05:49:52
【问题描述】:
我想并行运行方法 A 和方法 B1。这是有效的。但是如何在 B1 完成后运行方法 B2?
class Program
{
static void Main(string[] args)
{
//var firstTask = Task.Factory.StartNew(() => MethodB1());
//var secondTask = firstTask.ContinueWith( (antecedent) => MethodB2());
Action[] actionsArray =
{
() => MethodA(),
() => MethodB1(),
};
Parallel.Invoke(actionsArray);
}
private static void MethodA()
{
Console.WriteLine("A");
// more code is running here (30 min)
}
private static void MethodB1()
{
Console.WriteLine("B1");
// more code is running here (2 min)
}
private static void MethodB2()
{
Console.WriteLine("B2");
}
}
编辑: 我希望下面的例子能停止混淆。 ;)
A -> A -> A -> A -> A -> A -> A -> A -> A -> A -> A -> A -> A -> A
B1 -> B1 -> B1 -> B1 -> B1 -> B2 -> B2 -> B2
【问题讨论】:
-
您是否考虑过来自 Tasks 的异步和等待?
-
任务 task = new Task(doWork);任务.开始();任务 newTask = task.ContinueWith(doMoreWork);像这样的东西也应该有效,对吧?
-
你的方法是做什么的?他们是执行一些繁重的计算还是访问一些外部资源(数据库、Web 服务、文件系统......)?
-
@Fabio 请查看我的编辑。我与一些物联网设备进行通信并进行分析。
-
我刚刚了解到,在 C# 7.1 中,您现在可以在 main 中使用异步!
标签: c# task task-parallel-library