首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步任务同步

异步任务同步
EN

Stack Overflow用户
提问于 2015-11-25 15:17:32
回答 1查看 51关注 0票数 1

我有三个异步任务,它们需要按照这样的顺序先完成,如果第一个任务完成了,那么开始执行第二个任务,当第二个任务完成时,开始执行第三个异步任务。但我认为我的解决办法不是很好。你能提出更好的建议吗?

代码语言:javascript
复制
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");
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-25 15:21:20

现有代码无法工作,因为您可能根本不执行其余的代码,或者并行执行方法,这正是您想要防止的。

这是怎么回事?

代码语言:javascript
复制
Task.Run(() => {
 F1();
 F2();
 F3();
});

如果你想的话,你可以做异步。

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33920128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档