In my last post about async and Await, I forgot to mention to use Task<TResult>.Result to pause the control flow and get the results immediately. In these code blocks, I showed two locations to use Task<TResult>.Result, and location 2 is the preferred location since we are taking advantage of async programming.

 

static void Main(string[] args)
{
  Console.WriteLine("Main ThreadId: "
    + Thread.CurrentThread.ManagedThreadId + ", start" + "\r\n");

  AsyncAwaitTest aa = new AsyncAwaitTest();
  Task<int>[] tasks = new Task<int>[5];
  for (int i = 1; i <=5; i++)
  {
    tasks[i-1] = aa.GetStringAsync(i);
    // Location 1
    // If we uncomment the following line, it will force the program 
    // to sync mode and get the result immediately 
    // Console.WriteLine("Task : " + i + ": " + tasks[i - 1].Result);
  }

  Console.WriteLine("Main ThreadId: " 
    + Thread.CurrentThread.ManagedThreadId 
    + ", control back (UI responsive)." + "\r\n");

    for (int i = 1; i <=5; i++) 
    { 
        // Location 2
        // The preferred location 
        // since we are taking advantage of async programmin
        Console.WriteLine("Task : " + i + ": " + tasks[i - 1].Result); 
    } 

  Console.ReadKey();
}
public class AsyncAwaitTest
{
  public async Task GetStringAsync(int workerNumber)
  {
    Console.WriteLine("Worker #" + workerNumber + ", ThreadId: "
      + Thread.CurrentThread.ManagedThreadId
      + ", begin to process tons of data here ... ");
    var httpClient = new HttpClient();
    Task getStringAsync = 
    httpClient.GetStringAsync("http://msdn.microsoft.com");
    string content = await getStringAsync;
    int length = content.Length;
    Console.WriteLine("Worker #" + workerNumber + ", ThreadId: "
      + Thread.CurrentThread.ManagedThreadId + ", finished");
    return length;
  } 
}
Advertisements