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