meeheecaan meeheecaan - 1 month ago 6
C# Question

How do I actually write/end an async method in c#?

I get that I need to await thing in an

async
marked method to make it asynchronous, but I don't get how to actually end the hole it makes.

static async void Example()
{
int t = await getIntAsync();
WriteLine($"computer: {t}");
}


Since getIntAsync is marked async I have to await in that method or I get a warning. But oh no in the method I await on in getIntAsync I have to mark that as aasync, then unless there is an await in there I get a warning. And so on and so forth to infinity it seems. How do I just make it stop?

I've had a few people tell me to put

await Task.Delay(1000);


In my code, but I know the answer can't be as smelly as putting a delay of a second in all my production code.

A couple others said a task method to end it such as

static Task task()
{
//code
}


But unless I mark that
async
it throws the same warning that got me into this confusion. I know

static Task task()
{
//code
return Task.FromResult(0);
}


Technically it works, but again that seems too much of a code smell to have all over production.

I just don't get it...

EDIT:
Because it was asked for. I know its a very trivial method, but its also just one I'm using for practice.

static async Task<int> getIntAsync()
{

Console.Write("Enter the number: ");
int n = int.Parse(Console.ReadLine());
return n;

}

Answer

The following is needed (async keyword is required and so is the await, it's simply best practice):

  1. The Async keyword
  2. The Await keyword
  3. Some process that you want to work independently while the asynchorous process runs.
  4. Typically, you return value comes from your await task (which should fill in the end hole).

Here is example using a StreamReader,

async Task<string> GetStringFromReaderAsync()
{
  Streamreader sr = new StreamReader("filename.txt");

     Task<string> getStringTask = sr.ReadLineAsync("filepath");

    //Allow user to continue with some other work.
     DoFileLookup();

  string result = await sr.getStringTask();

  return result.ToString();

}

More information here: https://msdn.microsoft.com/en-us/library/system.io.streamreader.readlineasync(v=vs.110).aspx

More about Async and Await: https://msdn.microsoft.com/en-us/library/mt674882.aspx

Comments