Get result from Async task - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Async

Description

Get result from Async task

Demo Code

using System;/*from  w  w  w  . ja v  a2  s . c om*/
using System.ComponentModel;
using System.Threading.Tasks;
class EagerArgumentValidation3
{
   static void Main()
   {
      MainAsync().GetAwaiter().GetResult();
   }
   static async Task MainAsync()
   {
      Task<int> task = ComputeLengthAsync(null);
      Console.WriteLine("Fetched the task");
      int length = await task;
      Console.WriteLine("Length: {0}", length);
   }
   static Task<int> ComputeLengthAsync(string text)
   {
      if (text == null)
      {
         throw new ArgumentNullException(nameof(text));
      }
      return Impl(text);
      async Task<int> Impl(string t)
      {
         await Task.Delay(500);
         return t.Length;
      }
   }
}

Result


Related Tutorials