Populating list separately using async and await

1.2k Views Asked by At

I am new to C# and now I am trying to learn async and await by coming up with my own example. But I am having trouble implementing it. Basically I stole this example from MSDN: https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx

But in the main method, instead of what is there, I put:

static void Main(string[] args)
    {

        Person[] pArray = new Person[100];

        //populate first 50 people
          //TODO: USE ASYNC
        //populate last 50 people
          //TODO: USE ASYNC
        //await here
        People peopleList = new People(pArray);

        //do some linq
        Console.ReadKey();

    }

I don't really know how to implement the TODO part (I am not sure if this is how you to it either). Should I create a task method that is parallel to main? But the pArray won't be global in this way and the task function shouldn't be able to modify the variable, right? I was wondering how you could implement this. Any tips will be appreciated!

Thanks!

1

There are 1 best solutions below

0
Stephen Cleary On

It's far easier to learn async/await if you start by making I/O-bound operations asynchronous. Just creating People and adding them to an array is CPU-bound, not I/O-bound.

For async, you want to start with I/O. For example, you may want to download Google's homepage:

var client = new HttpClient();
var result = await client.GetStringAsync("http://www.google.com/");

Also, learning await is easier with a UI app rather than a Console app. So stick the code above in a button click event and see what happens.