Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Understanding Async / Await

Understanding Async / Await

Scheduled Pinned Locked Moved C#
questiontutorial
3 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Z Offline
    Z Offline
    zephaneas
    wrote on last edited by
    #1

    I am trying to understand Async, and I have 2 examples, but I don't see the difference: Example 1

        static string sampleFile = @"C:\\Projects\\Sandbox\\Async1\\Async1\\somefile.txt";
    
        static void Main(string\[\] args)
        {
            Console.WriteLine("Task 1 started");
    
            Task task = new Task(ReadTheFile);
            task.Start();
            task.Wait();
    
    
            Console.WriteLine("The READ task was started");
            Console.ReadLine();
        }
    
        static void ReadTheFile()
        {
            int count = 0;
    
            using (StreamReader reader = new StreamReader(sampleFile))
            {
                Console.WriteLine("Reading the file XXXX.");
                string v = reader.ReadToEnd();
    
                count += v.Length;
            }
    
            Console.WriteLine("Count: " + count);
        }
    

    Example 2

        static void Main(string\[\] args)
        {
            Console.WriteLine("Task 1 started");
    
            Task task = new Task(ProcessDataAsync);
            task.Start();
            task.Wait();
    
    
            Console.WriteLine("The READ task was started");
            Console.ReadLine();
        }
    
    
        static async void ProcessDataAsync()
        {
            Task task = HandleFileAsync(sampleFile);
    
            Console.WriteLine("Getting ready to read the file.");
    
            int x = await task;
            Console.WriteLine("Count: " + x);
        }
    
    
        static async Task HandleFileAsync(string file)
        {
            Console.WriteLine("HandleFile enter");
            int count = 0;
    
            using (StreamReader reader = new StreamReader(file))
            {
                Console.WriteLine("Reading the file.");
                string v = await reader.ReadToEndAsync();
    
                count += v.Length;
            }
    
            Console.WriteLine("HandleFile exit");
            return count;
        }
    

    They both read in a text file with 1,000,000 lines. The first one actually seems faster. What is the real difference here? Thanks

    F Richard DeemingR 2 Replies Last reply
    0
    • Z zephaneas

      I am trying to understand Async, and I have 2 examples, but I don't see the difference: Example 1

          static string sampleFile = @"C:\\Projects\\Sandbox\\Async1\\Async1\\somefile.txt";
      
          static void Main(string\[\] args)
          {
              Console.WriteLine("Task 1 started");
      
              Task task = new Task(ReadTheFile);
              task.Start();
              task.Wait();
      
      
              Console.WriteLine("The READ task was started");
              Console.ReadLine();
          }
      
          static void ReadTheFile()
          {
              int count = 0;
      
              using (StreamReader reader = new StreamReader(sampleFile))
              {
                  Console.WriteLine("Reading the file XXXX.");
                  string v = reader.ReadToEnd();
      
                  count += v.Length;
              }
      
              Console.WriteLine("Count: " + count);
          }
      

      Example 2

          static void Main(string\[\] args)
          {
              Console.WriteLine("Task 1 started");
      
              Task task = new Task(ProcessDataAsync);
              task.Start();
              task.Wait();
      
      
              Console.WriteLine("The READ task was started");
              Console.ReadLine();
          }
      
      
          static async void ProcessDataAsync()
          {
              Task task = HandleFileAsync(sampleFile);
      
              Console.WriteLine("Getting ready to read the file.");
      
              int x = await task;
              Console.WriteLine("Count: " + x);
          }
      
      
          static async Task HandleFileAsync(string file)
          {
              Console.WriteLine("HandleFile enter");
              int count = 0;
      
              using (StreamReader reader = new StreamReader(file))
              {
                  Console.WriteLine("Reading the file.");
                  string v = await reader.ReadToEndAsync();
      
                  count += v.Length;
              }
      
              Console.WriteLine("HandleFile exit");
              return count;
          }
      

      They both read in a text file with 1,000,000 lines. The first one actually seems faster. What is the real difference here? Thanks

      F Offline
      F Offline
      F ES Sitecore
      wrote on last edited by
      #2

      Your main problem is in thinking that async is faster. The thing that takes the time is reading the file and both examples do that. The only difference is that in the second example the thread is freed up to other things while it waits for the task to complete. You're only going to see any benefit in doing this if your system is under a lot of load and doing a lot of heavy tasks. Further more, how much benefit you see with asynch processing depends on how many cores etc the machine has. While the asynch tasks may free up your threads, that comes at a cost too so it depends on if the benefit if the asynch code outweights the extra cost. So in your example running a single time you're getting no benefit from the asynch calls, but you're getting the overhead involved in the thread switching about. If you want to time your code to see if there are any benefits to one thing over another then you can use the System.Diagnostics.Stopwatch class.

      1 Reply Last reply
      0
      • Z zephaneas

        I am trying to understand Async, and I have 2 examples, but I don't see the difference: Example 1

            static string sampleFile = @"C:\\Projects\\Sandbox\\Async1\\Async1\\somefile.txt";
        
            static void Main(string\[\] args)
            {
                Console.WriteLine("Task 1 started");
        
                Task task = new Task(ReadTheFile);
                task.Start();
                task.Wait();
        
        
                Console.WriteLine("The READ task was started");
                Console.ReadLine();
            }
        
            static void ReadTheFile()
            {
                int count = 0;
        
                using (StreamReader reader = new StreamReader(sampleFile))
                {
                    Console.WriteLine("Reading the file XXXX.");
                    string v = reader.ReadToEnd();
        
                    count += v.Length;
                }
        
                Console.WriteLine("Count: " + count);
            }
        

        Example 2

            static void Main(string\[\] args)
            {
                Console.WriteLine("Task 1 started");
        
                Task task = new Task(ProcessDataAsync);
                task.Start();
                task.Wait();
        
        
                Console.WriteLine("The READ task was started");
                Console.ReadLine();
            }
        
        
            static async void ProcessDataAsync()
            {
                Task task = HandleFileAsync(sampleFile);
        
                Console.WriteLine("Getting ready to read the file.");
        
                int x = await task;
                Console.WriteLine("Count: " + x);
            }
        
        
            static async Task HandleFileAsync(string file)
            {
                Console.WriteLine("HandleFile enter");
                int count = 0;
        
                using (StreamReader reader = new StreamReader(file))
                {
                    Console.WriteLine("Reading the file.");
                    string v = await reader.ReadToEndAsync();
        
                    count += v.Length;
                }
        
                Console.WriteLine("HandleFile exit");
                return count;
            }
        

        They both read in a text file with 1,000,000 lines. The first one actually seems faster. What is the real difference here? Thanks

        Richard DeemingR Offline
        Richard DeemingR Offline
        Richard Deeming
        wrote on last edited by
        #3

        Your second example is not the correct way to use async. You should avoid async void wherever possible: Avoid async void methods[^] You might also get better performance if you use an asynchronous Stream to read the file. Try this:

        static void Main(string[] args)
        {
        Console.WriteLine("Task 1 started");

        Task task = ProcessDataAsync();
        task.Wait();
        
        Console.WriteLine("The READ task was started");
        Console.ReadLine();
        

        }

        static async Task ProcessDataAsync()
        {
        Task task = HandleFileAsync(sampleFile);

        Console.WriteLine("Getting ready to read the file.");
        
        int x = await task;
        Console.WriteLine("Count: " + x);
        

        }

        static async Task HandleFileAsync(string file)
        {
        Console.WriteLine("HandleFile enter");
        int count = 0;

        using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous))
        using (StreamReader reader = new StreamReader(stream))
        {
            Console.WriteLine("Reading the file.");
            string v = await reader.ReadToEndAsync();
            count += v.Length;
        }
        
        Console.WriteLine("HandleFile exit");
        return count;
        

        }


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

        1 Reply Last reply
        0
        Reply
        • Reply as topic
        Log in to reply
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes


        • Login

        • Don't have an account? Register

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • World
        • Users
        • Groups