Suman
Suman

Reputation: 11

Nested Await operations are failing in ..NET 4.5

I am trying to develop a Windows 8 Metro style application. I have got the following use case:

async void dofileop()
{
  await writedatatofile();          
  printdata();
}

IAsyncAction writedatatofile()
{
  readdatafromfile();
  //play with data
  return FIleIO.WriteData();
}

async void readdatafromfile()
{
    await FileIO.readdata();
    operation1
    operation 2
}

Here after executing await FileIO.readdata();, the control is immediately going to //play with data instead of operation1 and operation2. After executing printdata() the control is coming back to operation1 and operation2.

How can I fix these kind of issues?

Upvotes: 1

Views: 499

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457137

As per the usecase all the statements in readdatafromfile() should be executed before control is going back to writedatatofile().

That's not how async methods work. You may want to read my async/await intro. An async method will return to its caller when it awaits some operation that isn't completed (e.g., FileIO.readdata).

As a general rule, have your async methods return Task, and then await those Tasks in other async methods, like this:

async Task dofileop()
{
  await writedatatofile();          
  printdata();
}

async Task writedatatofile()
{
  await readdatafromfile();
  //play with data
  await FIleIO.WriteData();
}

async Task readdatafromfile()
{
  await FileIO.readdata();
  operation1
  operation 2
}

Also my constrain is not to change the syntax of the IAsyncAction writedatatofile() function.

That's just a bit more convoluted:

async Task dofileop()
{
  await writedatatofileAsync();          
  printdata();
}

IAsyncAction writedatatofile()
{
  return writedatatofileAsync().AsAsyncAction();
}

async Task writedatatofileAsync()
{
  await readdatafromfile();
  //play with data
  await FIleIO.WriteData();
}

async Task readdatafromfile()
{
  await FileIO.readdata();
  operation1
  operation 2
}

Upvotes: 2

Related Questions