0

I'm trying to understand how asynchronous works. This is my code:

class Program
{
    static void Main(string[] args)
    {
        Task<string> strReturned = returnStringAsync();
        Console.WriteLine("hello!");
        string name = await strReturned; //error: The 'await' operator can only be used 
                                         //within an async method. Consider marking this 
                                         //method with the 'async' modifier and changing 
                                         //its return type to 'Task'

        Console.WriteLine(name);
    }

    static async Task<string> returnStringAsync()
    {
        Thread.Sleep(5000);
        return "Richard"; 
    }
}

Any thing wrong?

Richard77
  • 20,343
  • 46
  • 150
  • 252

1 Answers1

1

This works

class Program
{
    static void Main(string[] args)
    {
        Task<string> str = returnStringAsync();
        Console.WriteLine("hello!");

        string name = str.Result;

        Console.WriteLine(name);
    }

    static async Task<string> returnStringAsync()
    {
        await Task.Delay(5000);
        return "Richard"; 
    }
}
Richard77
  • 20,343
  • 46
  • 150
  • 252
  • 2
    Yes, this works, but it's pretty much the only case where it's a good idea to call `Result` (or `Wait()`) on an `async` `Task`. In most other cases, doing that would cause a deadlock. – svick Jan 06 '14 at 10:43
  • @svick. Then give a better way to write this code. In fact, this is the very first time I've even written a code on async and await. Everything is still new to me in that field. – Richard77 Jan 06 '14 at 23:05
  • In this specific case (console application running `async` code), using `Result` *is* the right way. But in most other cases, it's not. – svick Jan 07 '14 at 01:43