question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked lextm commented

C# What is objective and advantage of Async Await function

Anyone please post few sample code from where one can understand the advantages of using Async/Await function.

a) it is just only that UI will be responsive ?
b) current thread or main thread will not be blocked and can take more request

these are two benefit for which people use Async/Await function. ?

1) one sample code where Async/Await will not be used and post second one of same routine where Async/Await will be used to show the advantage of Async/Await.

Thanks

dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Neither Async nor Await are functions. Their use are difficult to understand. I have been programing for half a century and it is difficult for me to understand how they work. There are no easy answers.

0 Votes 0 ·

With or without async/await, you can write multithreading applications (various approaches from Windows native API, Thread and ThreadPool, BeginXXX/EndXX, and Task based API), and async/await just makes the syntax clean and easy to understand/maintain. That's why it has been stolen by all other major programming languages ever since. One WinForms example can be found in https://blog.lextudio.com/how-to-replace-backgroundworker-with-async-await-and-tasks-80d7c8ed89dc

0 Votes 0 ·
Castorix31 avatar image
0 Votes"
Castorix31 answered

This article explains it well : Async and Await In C#
or MSDN : Asynchronous programming with async and await


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered karenpayneoregon commented

Perhaps some solid code samples will assist in understanding Asynchronous programming.

Then there is writing custom extensions

 namespace AsyncSimple.Classes
 {
     public static class Helpers
     {
         public static async IAsyncEnumerable<int> RangeAsync(this int start, int count, [EnumeratorCancellation] CancellationToken cancellationToken = default)
         {
    
             for (int index = 0; index < count; index++)
             {
                 if (cancellationToken.IsCancellationRequested) cancellationToken.ThrowIfCancellationRequested();
                 await Task.Delay(GlobalStuff.TimeSpan, cancellationToken);
                 yield return start + index;
             }
         }
    
     }
 }


Or used when traversing a directory structure keeping the user interface responsive.

 namespace FileHelpers
 {
     public class Operations
     {
         public delegate void OnException(Exception exception);
         public static event OnException OnExceptionEvent;
           
         public delegate void OnUnauthorizedAccessException(string message);
         public static event OnUnauthorizedAccessException UnauthorizedAccessExceptionEvent;      
         public delegate void OnTraverseFolder(string status);
    
         public static event OnTraverseFolder OnTraverseEvent;
         public delegate void OnTraverseExcludeFolder(string sender);
         public static event OnTraverseExcludeFolder OnTraverseExcludeFolderEvent;       
         public static bool Cancelled = false;
         public static async Task RecursiveFolders(DirectoryInfo directoryInfo, string[] excludeFileExtensions, CancellationToken ct)
         {
    
             if (!directoryInfo.Exists)
             {
                 OnTraverseEvent?.Invoke("Nothing to process");
    
                 return;
             }
    
             if (!excludeFileExtensions.Any(directoryInfo.FullName.Contains))
             {
                 await Task.Delay(1, ct);
                 OnTraverseEvent?.Invoke(directoryInfo.FullName);
             }
             else
             {
                 OnTraverseExcludeFolderEvent?.Invoke(directoryInfo.FullName);
             }
    
             DirectoryInfo folder = null;
    
             try
             {
                 await Task.Run(async () =>
                 {
                                foreach (DirectoryInfo dir in directoryInfo.EnumerateDirectories())
                                {
    
                                    folder = dir;
    
                                    if ((folder.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || 
                                        (folder.Attributes & FileAttributes.System) == FileAttributes.System ||
                                        (folder.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) {
                                        OnTraverseExcludeFolderEvent?.Invoke($"* {folder.FullName}");
    
                                        continue;
    
                                    }
    
                                    if (!Cancelled)
                                    {
    
                                        await Task.Delay(1);
                                        await RecursiveFolders(folder, excludeFileExtensions, ct);
    
                                    }
                                    else
                                    {
                                        return;
                                    }
    
                                    if (ct.IsCancellationRequested)
                                    {
                                        ct.ThrowIfCancellationRequested();
                                    }
    
                                }
                 }, ct);
    
             }
             catch (Exception ex)
             {
                 if (ex is OperationCanceledException)
                 {
                     Cancelled = true;
                 }
                 else if (ex is UnauthorizedAccessException)
                 {
                     UnauthorizedAccessExceptionEvent?.Invoke($"Access denied '{ex.Message}'");
                 }
                 else
                 {
                     OnExceptionEvent?.Invoke(ex);
                 }
             }
         }
    
         public static void RecursiveFolders(string path, int indentLevel)
         {
    
             try
             {
    
                 if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
                 {
    
                     foreach (string folder in Directory.GetDirectories(path))
                     {
                         Debug.WriteLine($"{new string(' ', indentLevel)}{Path.GetFileName(folder)}");
                         RecursiveFolders(folder, indentLevel + 2);
                     }
    
                 }
    
             }
             catch (UnauthorizedAccessException unauthorized)
             {
                 Debug.WriteLine($"{unauthorized.Message}");
             }
         }
    
     }
    
 }








· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks Madam.

Tell me please point wise the good side or advantage of Async / Await programming.

here i mention two good side that is

a) it is just only that UI will be responsive ?
b) current thread or main thread will not be blocked and can take more request

other than above 2 points what other reason exist for Async / Await programming ? can you please mention.

Thanks

0 Votes 0 ·

Read the links posted above : everything is explained, with great samples

0 Votes 0 ·

In my last reply I mentioned two forms of cancellation, there is also progress reporting (yeah BackGroundWorker component has this but is limited)

a) it is just only that UI will be responsive ?

No, allows say doing a builder pattern and WhenAll, WhenAny to ensure code works in a proper order

b) current thread or main thread will not be blocked and can take more request

Sure

See also Event-based Asynchronous Pattern

 private static async Task AsyncMethod(IProgress<int> progress, CancellationToken ct)
 {
    
     for (int index = 100; index <= 120; index++)
     {
         //Simulate an async call that takes some time to complete
         await Task.Delay(500, ct);
    
         if (ct.IsCancellationRequested)
         {
             ct.ThrowIfCancellationRequested();
         }
    
         progress?.Report(index);
    
     }
    
 }
 private void ReportProgress(int value)
 {
     StatusLabel.Text = value.ToString();
     TextBox1.Text = value.ToString();
 }


0 Votes 0 ·

Where is the call for AsyncMethod() function ? why there ? mark in the function call like progress?.Report(index); ?

what is the meaning of ? mark when calling a function ? please guide me Madam.

0 Votes 0 ·
Show more comments
AgaveJoe avatar image
0 Votes"
AgaveJoe answered TZacks-2728 commented

Tell me please point wise the good side or advantage of Async / Await programming.

A computer's internal hardware and APIs are all asynchronous. It makes sense to write programs that work with the hardware and APIs. That's where TAP comes into play. Task asynchronous programming model (TAP) is a C# programming pattern.

It is important to understand that asynchronous programming has been around a very long time and writing asynchronous logic has always been the recommendation. The problems is asynchronous is a difficult concept to understand and previous asynchronous programming patterns closely mirrored an asynchronous transaction. These previous patterns require block of code to make a call and another block of code to handle the results; a callback. Understandably, two code blocks for every method call creates a complex code base that is difficult to maintain and debug. TAP solves the issues of previous C# asynchronous patterns by making the code appear synchronous to the developer while under the covers the compiler creates complex asynchronous code. The code is easier to write but TAP programming patterns must be followed along with a solid understanding of what asynchronous means. The links in this thread and your two duplicates threads illustrate these concepts.

The key take away is always write asynchronous logic when executing API/hardware tasks that are asynchronous. These are non-cpu tasks like executing a SQL script or calling an HTTP service.

a) it is just only that UI will be responsive ?

That's a fairly narrow view. Asynchronous programming make more efficient use of system resources. Web developers also use the TAP pattern.

b) current thread or main thread will not be blocked and can take more request

That's the general idea. You get to squeeze the most performance out of a system.

other than above 2 points what other reason exist for Async / Await programming ? can you please mention.

Start by reading the links the community has provided in this thread and your duplicate posts.













· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes i will read. many thanks for answer me.
Sir Async / Await is good for CPU bound job or IO bound job ? Thanks

0 Votes 0 ·
Bruce-SqlWork avatar image
1 Vote"
Bruce-SqlWork answered

there are two uses of async/await

1) do additional work while an async i/o operation is in progress. this can be extra computing or additional i/o

2) manage parallel tasks via threads. this is helpful for cpu bound tasks, and allows more than one cpu processor to be used.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.