简体   繁体   中英

How to wait for one task to finish before calling another without blocking?

Trying to do something like this:

Task task1 = Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, task1Data, 0, task1Data.Length, null, TaskCreationOptions.AttachedToParent);

Task task2 = Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, task2Data, 0, task2Data.Length, null, TaskCreationOptions.AttachedToParent);

But correct me if I'm wrong but isn't there a chance task2 could execute while or before task1 executes? I want something like ContinueWith where the code doesn't block but task2 still does not execute until task1 completes.

I tried doing Task task2 = new Task(...) so I could call task1.ContinueWith(task2); but it wouldn't compile. I'm pretty sure I have to use FromAsync (which runs automatically). I think putting task1.Wait(); between the two lines would work but wouldn't that block? Trying to stay away from blocking..

Any advice?

task1.ContinueWith(t=>Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, task2Data, 0, task2Data.Length, null, TaskCreationOptions.AttachedToParent));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM