如何并行运行2个任务并在一个特定任务结束时得到通知(我的情况是列表中的第一个任务)
当前我正在使用以下代码:
await Task.WhenAny(A.Play(cancel), B.Play(cancel));
代码应在A.Play(取消)结束时返回,而不是在b.Play(取消)结束时返回。
WhenAny不起作用,因为B可能在A之前结束。 WhenAll不起作用,因为它可能是B是一个无尽的任务。
答案 0 :(得分:2)
我相信这会做您想要的。任务将并行运行,但是您首先要等待aTask,因此仅当aTask返回时才返回。然后,您可以包括单独的逻辑来等待bTask。
import java.security.AccessController;
clearModel(model);
model.component().create("comp1", true);
model.component("comp1").geom().create("geom1", 3);
model.component("comp1").mesh().create("mesh1");
model.component("comp1").geom("geom1").create("imp1", "Import");
AccessController.doPriviledged(
model.component("comp1").geom("geom1").feature("imp1").set("filename", "C:\\Users\\peter\\STL_Examples\\beam_0.STL")
);
model.component().create("mcomp1", "MeshComponent");
model.geom().create("mgeom1", 3);
model.mesh().create("mpart1", "mgeom1");
with(model.component("comp1").geom("geom1").feature("imp1"));
set("mesh", "mpart1");
endwith();
model.mesh("mpart1").create("imp1", "Import");
with(model.mesh("mpart1").feature("imp1"));
set("filename", "C:\\Users\\peter\\STL_Examples\\beam_0.STL");
endwith();
with(model.component("comp1").geom("geom1").feature("imp1"));
set("meshfilename", "");
endwith();
model.mesh("mpart1").run();
答案 1 :(得分:1)
您可以使用
B.Play()
没有await
即可运行B
,而无需等待其结束然后再执行
await A.Play()
答案 2 :(得分:0)
您可以将“ A.Play”包装在新的任务方法中,该方法将在“ A.Play”完成后执行您想要的任何事情。
async Task CallingMethod()
{
await Task.WhenAny(WrapperA(), B.Play(cancel));
}
async Task WrapperA()
{
await A.Play(cancel)
// Here you can fire an event or set the cancellation token
// Or whatever you want.
}