Head wrapping around asynchronous wait

Sorry for the newbies' egregious question. There is something in Asinka and Iโ€™m waiting for what I donโ€™t understand.

In order for the method to be asynchronous, it must wait for a return from the task / method, which is also asynchronous. Right? But at some point there should not be a task that is not asynchronous or does not expect anything?

I read tutorials like these two:

https://msdn.microsoft.com/en-us/magazine/hh456401.aspx

https://msdn.microsoft.com/en-us/library/mt674882.aspx

And I looked here a lot of other topics. But I still do not understand. I will try to give a simple example. Say I want to write a value to a column in a database:

 public async Task<SimpleObject> ExecuteAsync(int rowID, string value)
 {
    return await WriteToDB(int rowID, string value);
 }

So far so good. But here where I get lost:

 public async Task<SimpleObject> WriteToDB(int rowID, string value)
 {
      var dataRow = context. /// use linq to get a row with rowID
      dataRow.SomeColumn = value
      context.SaveChanges();
      var simpleObject = new SimpleObject();
      simpleObject.success = true;
      return simpleObject;
 }

 public class SimpleObject
 {
    public bool success {get;set;}
 }

VS, WriteToDB() await . , . , await WriteToDB().

+4
3

.SaveChangesAsync.

 public async Task<SimpleObject> WriteToDB(int rowID, string value)
 {
      var dataRow = context. 
      dataRow.SomeColumn = value
      await context.SaveChangesAsync(); //change this line
      var simpleObject = new SimpleObject();
      simpleObject.success = true;
      return simpleObject;
 }
+3

EntityFramework , SaveChangesAsync ToListAsync, async " " Task Task<T>, .

, async :

public async Task<SimpleObject> WriteToDB(int rowID, string value)
{
    var dataRow = await context.table.SingleAsync(item =>item.Id = /*some value*/);
    dataRow.SomeColumn = value
    await context.SaveChangesAsync();
    var simpleObject = new SimpleObject();
    simpleObject.success = true;
    return simpleObject;
}
+2

.

, - " SaveChangesAsync SaveChanges".

" async", :

  • - . -. .
  • API API await. SaveChanges await SaveChangesAsync.
  • async, . SimpleObject WriteToDB(..) async Task<SimpleObject> WriteToDBAsync(..).

Repeat steps (2) and (3) until the application is assembled. In this example, step (2) will change the call return WriteToDB(int rowID, string value);to return await WriteToDBAsync(int rowID, string value);, and step (3) will change SimpleObject Execute(..)to async Task<SimpleObject> ExecuteAsync(..).

It is much easier to apply async/ awaitin this way, starting from the lowest levels and increasing from there.

But at some point there should not be a task that is not asynchronous or does not expect anything?

Yes. Least-level methods are usually implemented using TaskFactory.FromAsyncor TaskCompletionSource<T>.

+1
source

Source: https://habr.com/ru/post/1675948/


All Articles