异步任务同步

时间:2015-11-25 15:17:32

标签: c# multithreading asynchronous

我有三个异步任务需要按照这样的顺序完成首先,比如First完成,开始做第二个,当第二个完成时开始做第三个。但我认为我的解决方案并不是很好。你能提出更好的建议吗?

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 个答案:

答案 0 :(得分:5)

现有代码不起作用,因为您可能根本不执行剩余代码,或者并行执行您想要阻止的方法。

这有什么问题?:

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

如果需要,可以将其设为异步。

另外,您可能不知道99%的案例中IAsyncResult已过时。