Awaiting custom functions

I'm trying to get my head around the new async features in C#, and so far the strangest thing I've noticed is that every example for async features has a function that awaits another async function defined in the framework, but none of them have custom code.

For example, what I want to is create an object from each line in a text file, but asynchronously, so that the UI thread doesn't freeze:

async Task Read()
{
    string[] subjectStrings = File.ReadAllLines(filePath);
    for (int i = 0; i < subjectStrings.Length; i++)
    {
        Task<Subject> function = new Task<Subject>(code => new Subject((string)code), subjectStrings[i]);
        try
        {
            Subject subject = await function;
            subjects.Add(subject);
        }
        catch (Exception ex)
        {
            debugWriter.Write("Error in subject " + subjectStrings[i]);
            continue;
        }
    }
}

As you can see, I define a task that creates a new Subject object based on a line in the text file, and then await this task. If I do this, the debugger gets up to the await line, and then just stops. No more code is run, as far as I know.

If I was using the old async features, I'd just use Task.ContinueWith() and add a callback lambda that adds the subject to the list, and be on my way.

So my questions are:

  1. Why does this code not work? How are you supposed to make a custom async method that doesn't use any async methods itself?
  2. How are you supposed to use async methods? You can't use await unless you're in an async function, and you're not supposed to call an async method without await, so how do you first call that method from a synchronous method?
Jon Skeet
people
quotationmark

You're not starting the task - so it will never finish.

Use Task.Run instead of new Task and it will create and start the task for you.

Note that you're still reading the file synchronously, which isn't ideal... and if your Subject constructor really takes that long to complete, I'd question whether it should be a constructor.

people

See more on this question at Stackoverflow