In c#, I have to ensure that a certain block of code in a handler will only be executed after several threads finish. 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.
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
. Any ideas on how I can solve this problem?
startMethod is fire and forget, because async Tasks are'nt collected in 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.
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());