1

I have three async task's which need to complete in such sequence First, than if First is completed, Start doing Second, and when Second is completed start doing Third. But I think that my solution is not very good. Can you suggest something better?

namespace WpfApplication215 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new AsyncWork(); } } public class AsyncWork { public List<int> Items { get; set; } public AsyncWork() { Action FirstPart = new Action(ComputeFirstpart); IAsyncResult result1 = FirstPart.BeginInvoke(null, null); if (!result1.AsyncWaitHandle.WaitOne(0, false)) { Action SecondPart = new Action(ComputeSecondPart); IAsyncResult result2 = SecondPart.BeginInvoke(null, null); if (!result2.AsyncWaitHandle.WaitOne(0, false)) { Action ThirdPart = new Action(ComputeThirdPart); IAsyncResult result3 = ThirdPart.BeginInvoke(null, null); } } } public void ComputeFirstpart() { Random rnd = new Random(); System.Threading.Thread.Sleep(rnd.Next(1000,5000)); Console.WriteLine("First Task Completed"); } public void ComputeSecondPart() { Random rnd = new Random(); System.Threading.Thread.Sleep(rnd.Next(1000, 5000)); Console.WriteLine("Second Task Completed"); } public void ComputeThirdPart() { Random rnd = new Random(); System.Threading.Thread.Sleep(rnd.Next(1000, 5000)); Console.WriteLine("Third Task Completed"); } } 

1 Answer 1

5

The existing code does not work because you might simply not execute the remaining code, or execute methods in parallel which is what you wanted to prevent.

What is wrong with this?:

Task.Run(() => { F1(); F2(); F3(); }); 

You can make that async if you want.

Also, you might not be aware that IAsyncResult is obsolete in 99% of the cases.

Sign up to request clarification or add additional context in comments.

2 Comments

@A191919 it appears to be working but I'm surprised it does at all. The timing should make it fail 99.9999% of the cases because WaitOne(0) should almost always fail. Update: WaitOne will return mostly false, so the checks go through and you are executing the methods in parallel. So in 99.999% of the cases you have a bug there.
Strongly agree on IAsyncResult - it is fully obsolete.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.