我有三个异步任务,它们需要按照这样的顺序先完成,如果第一个任务完成了,那么开始执行第二个任务,当第二个任务完成时,开始执行第三个异步任务。但我认为我的解决办法不是很好。你能提出更好的建议吗?
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");
}
}发布于 2015-11-25 15:21:20
现有代码无法工作,因为您可能根本不执行其余的代码,或者并行执行方法,这正是您想要防止的。
这是怎么回事?
Task.Run(() => {
F1();
F2();
F3();
});如果你想的话,你可以做异步。
另外,您可能不知道IAsyncResult在99%的情况下是过时的。
https://stackoverflow.com/questions/33920128
复制相似问题