I have the following utility:
class Worker
{
public void DoWorkAsync(Action callback)
{
Action work = () => Thread.Sleep(3000);
AsyncCallback asyncCallback = (result) => callback();
work.BeginInvoke(asyncCallback, null);
}
}
I use it like the following:
static void Main(string[] args)
{
var worker = new Worker();
worker.DoWorkAsync(() => Console.WriteLine("Completed."));
Console.WriteLine("Hello world!");
Console.ReadKey();
}
This will of course print Hello world! before Completed., since the worker works asynchronously.
My question is how can I block my thread so it should wait until the action is completed, then move on.
I know I can do it like this:
static void Main(string[] args)
{
var worker = new Worker();
worker.DoWorkAsync(() =>
{
Console.WriteLine("Completed.");
MoveOn();
});
Console.ReadKey();
}
static void MoveOn()
{
Console.WriteLine("Hello world!");
}
But since I have a bunch of cascaded async callbacks that should be executed one after the other (conditionally), I want them all to execute synchronously, so is there a more elegant way to wait for an async method that takes a callback as a param?
Note: Just to make sure, I cannot alter the behavior of the Worker class, its an external utility and I don’t have access to its code.
Update
In my particular scenario I’m trying to interact with user from the ViewModel and get responses from him. My code is executed in the view-model and there is a method controlling a chain of cascaded interactions, I want this method should decide whether to fire a certain interaction or not. I tried SLaxs’ answer, and also tried this but it doesn’t seem to work, any ideas on how to make the main method the only controller of the interactions?
Create a
ManualResetEvent, callSet()in the callback, and callWaitOne()to wait for the operation to finish.