A191919
A191919

Reputation: 3442

Async task synchronization

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");
    }
}

Upvotes: 1

Views: 55

Answers (1)

usr
usr

Reputation: 171178

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.

Upvotes: 5

Related Questions