Ryan Peschel
Ryan Peschel

Reputation: 11828

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?

Upvotes: 1

Views: 747

Answers (1)

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35146

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

Upvotes: 5

Related Questions