Search code examples
c#multithreadingasynchronousc#-4.0continuewith

Waiting on All Task Threads without having the Task Object


I have an application using .NET 4.0 (so no async/await available). I am writing tests for a method that uses service calls.

So for example, my test calls method A. Method A has an async service call to method B which returns a Task and we do all the processing in ContinueWith. Method A returns nothing.

The problem is that the main thread reaches the Assert call before the ContinueWith has a chance to finish so the test fails.

The way to get around this currently is doing Thread.Sleep(10) so that the ContinueWith has time to execute. This however poses plenty of issues, such as wasting time (which adds up when having hunders - thousands of tests) to tests failing on slower machines.

I would like to know if there is any way to do a sort of Thread.WaitAll() without actually having the Task objects as there's no way to get them. Changing the code is not an option so it must be done from the tests.

Note: I am aware of methods to do it if we have the Task/Thread objects, but I don't have access to them, so please do not mark it as a duplicate of those as it is not.


Solution

  • I would like to know if there is any way to do a sort of Thread.WaitAll() without actually having the Task objects as there's no way to get them.

    No, there is not a way to do this reliably.