Home > Enterprise >  execute async method in order
execute async method in order

Time:02-04

I am currently facing the problem either everything async or nothing.
I have a Task Append which in turn calls some io operations async to be able to execute faster.

If the io Operation is still running, Append waits for its completion before calling it again. This may lead to multiple Append instances to stack up.

The Append method should always execute order though. lets say I have the following code:

Append("this ");
Append("is ");
Append("an ");
Append("Example");

It would be nonsense if "this Exampleis an " came out. How do I prevent this from happening? Can I do that from within my Append class or do I have to await Append in my calling code?

CodePudding user response:

You should await every Append call. It will ensure that the current task completes before calling the next one.

Please note that naming your method Append doesn't imply its asynchronousness, and as such should be named AppendAsync

public void Append(string str)
{
    // some non-asynchronous logic
}

public async Task AppendAsync(string str)
{
    // some asynchronous logic
}

...

await AppendAsync("this ");
await AppendAsync("is ");
await AppendAsync("an ");
await AppendAsync("Example");
  •  Tags:  
  • Related