[英]How to wait for all threads created within a method
In c#, I have to ensure that a certain block of code in a handler will only be executed after several threads finish. 在c#中,我必须确保处理程序中的某个代码块只能在多个线程完成后执行。 Those threads are invoked from a method that is called in the same handler, immediately before the aforementioned block of code. 这些线程是从在上述代码块之前的同一个处理程序中调用的方法调用的。 The syntax used is related with the DBMS that I am using, namely Starcounter. 使用的语法与我正在使用的DBMS相关,即Starcounter。
Handle.GET("/path/to/HandlerStartTests", () =>
{
// some code
startMethod();
// some code that relies on what happens within startMethod
}
public static void startMethod()
{
QueryResultRows<PO> pos = Db.SQL<PO>("SELECT po FROM PO po");
foreach (var po in pos)
{
DbSession dbSession = new DbSession();
dbSession.RunAsync(() =>
{
// Do some stuff in the Starcounter database
});
}
}
This is for unit testing purposes, so I can't do any changes in the startMethod
. 这是出于单元测试目的,因此我无法对startMethod
进行任何更改。 Any ideas on how I can solve this problem? 关于如何解决这个问题的任何想法?
startMethod is fire and forget, because async Tasks are'nt collected in DbSession.RunAsync(). startMethod是火与遗忘,因为异步任务不是在DbSession.RunAsync()中收集的。 Without modifying this method there is no reference to the started Task's to wait for. 如果不修改此方法,则不会引用已启动的任务等待。
If this method could be modified one could wrap a sync call DbSession.Sync() if such is defined in a Task and wait for those tasks. 如果可以修改此方法,则可以包装同步调用DbSession.Sync(),如果在任务中定义了这样,并等待这些任务。
QueryResultRows<PO> pos = Db.SQL<PO>("SELECT po FROM PO po");
List<Task>tasks = new List<Task>();
foreach (var po in pos)
{
DbSession dbSession = new DbSession();
var task = Task.Run(()=>
dbSession.RunSync(() =>
{
// Do some stuff in the Starcounter database
}));
tasks.Add(Task);
}
Task.WaitAll(tasks.ToArray());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.