Here is a simple example:
public event EventHandler CookinDone = delegate{}; public void CoockinRequest(){ var indicator = new ActivityIndicator(); ActivityIndicator.Show("Oooo coockin' something cool"); var bw = new BackgroundWorker(); bw.DoWork += (sender, e) => CockinService.Cook(); bw.RunWorkerCompleted += (sender, e) => { indicator.Hide(); CookinDone.Invoke(this,null); }; bw.RunWorkerAsync(); }
Now, every time I use this method, I have to catch the CookinDone event and move on.
var cook = new Cook(); cook.CookinDone += (sender, e) => MessageBox.Show("Yay, smells good"); cook.CoockinRequest();
But how can I simplify this by making the return type of the method as Boolean and returning the result after the Cookin finishes?
if (CoockinRequest()) MessageBox.Show('Yay, smells even better');
If I put something like while (bw.IsBusy)
, it will close my ActivityIndicator, freeze the main thread, and I feel that this would be the worst thing. There are also some Monitor.Wait
things and some other things like TaskFactory
, but it all seems too complicated to use in simple scripts.
It may be different in different environments, for example, some approach is good for WPF applications, some for something else and something else, but there must be a common template is not it?
How do you do this?
Agzam source share