c# - 异步任务同步

标签 c# multithreading asynchronous

我有三个异步任务需要按这样的顺序完成,首先,如果第一个完成,则开始做第二个,当第二个完成时开始做第三个。但我认为我的解决方案不是很好。你能推荐一些更好的吗?

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

最佳答案

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

这有什么问题?:

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

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

此外,您可能不知道 IAsyncResult 在 99% 的情况下已过时。

关于c# - 异步任务同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33920128/

相关文章:

c# - 如何聚合 GroupBy 并等待结果

c - 为什么我们使用线程并一起选择

java - 指定超时后同步方法释放

java - 如何处理 Jetty 异常 - 长时间运行的 HTTP 请求超时,但它调用的进程永远不会终止并且 Jetty 不高兴

javascript - 无法在异步函数内分配对象属性

c# - 关于 SemaphoreSlim 与 A​​sync/Await 的使用

C# 只替换文件中的一个东西

c# - Quartz.Net cron触发器每月计划一次作业

c++ - PThread - 尽管调用了 pthread_join,但线程提前退出

c# - UserPrincipal.FindByIdentity 在 64 位 WinPE 下的 C# 中失败