Asynchronous programming with async, await, Task in C#

C# and .NET Framework (4.5 & Core) supports asynchronous programming using some native functions, classes, and reserved keywords.

Before we see what is asynchronous programming, let's understand what is synchronous programming using the following console example.

In the above example, the LongProcess() method is some long-running task such as reading a file from the server, calling a web API that returns a large amount of data or uploading or downloading a big file. It takes a little longer time to execute ( Thread.Sleep(4000) holds it for 4 seconds just to show long execution time). The ShortProcess() is a simple method that gets executed after the LongProcess() method.

The above program executes synchronously. It means execution starts from the Main() method wherein it first executes the LongProcess() method and then ShortProcess() method. During the execution, an application gets blocked and becomes unresponsive (You can see this in Windows-based applications mainly). This is called synchronous programming where execution does not go to next line until the current line executed completely.

What is Asynchronous Programming?

In asynchronous programming, the code gets executed in a thread without having to wait for an I/O-bound or long-running task to finish. For example, in the asynchronous programming model, the LongProcess() method will be executed in a separate thread from the thread pool, and the main application thread will continue to execute the next statement.

Microsoft recommends Task-based Asynchronous Pattern  to implement asynchronous programming in the .NET Framework or .NET Core applications using async , await keywords and Task or Task<TResult> class.

Now let's rewrite the above example in asynchronous pattern using async keyword.

In the above example, the Main() method is marked by the async keyword, and the return type is Task . The async keyword marks the method as asynchronous. Note that all the methods in the method chain must be async in order to implement asynchronous programming. So, the Main() method must be async to make child methods asynchronous.

The LongProcess() method is also marked with the async keyword which makes it asynchronous. The await Task.Delay(4000); holds the thread execute for 4 seconds.

Now, the program starts executing from the async Main() method in the main application thread. The async LongProcess() method gets executed in a separate thread and the main application thread continues execution of the next statement which calls ShortProcess() method and does not wait for the LongProcess() to complete.

async, await, and Task

Use async along with await and Task if the async method returns a value back to the calling code. We used only the async keyword in the above program to demonstrate the simple asynchronous void method.

The await keyword waits for the async method until it returns a value. So the main application thread stops there until it receives a return value.

The Task class represents an asynchronous operation and Task<TResult> generic class represents an operation that can return a value. In the above example, we used await Task.Delay(4000) that started async operation that sleeps for 4 seconds and await holds a thread until 4 seconds.

The following demonstrates the async method that returns a value.

In the above example, in the static async Task<int> LongProcess() method, Task<int> is used to indicate the return value type int. int val = await result; will stop the main thread there until it gets the return value populated in the result. Once get the value in the result variable, it then automatically assigns an integer to val .

An async method should return void ,  Task , or  Task<TResult> , where TResult is the return type of the async method. Returning void is normally used for event handlers. The async keyword allows us to use the await keyword within the method so that we can wait for the asynchronous method to complete for other methods which are dependent on the return value.

If you have multiple async methods that return the values then you can use await for all methods just before you want to use the return value in further steps.

In the above program, we do await result1 and await result2 just before we need to pass the return value to another method.

Thus, you can use async , await, and Task to implement asynchronous programming in .NET Framework or .NET Core using C#.

  • How to get the sizeof a datatype in C#?
  • Difference between String and StringBuilder in C#
  • Static vs Singleton in C#
  • Difference between == and Equals() Method in C#
  • How to loop through an enum in C#?
  • Generate Random Numbers in C#
  • Difference between Two Dates in C#
  • Convert int to enum in C#
  • BigInteger Data Type in C#
  • Convert String to Enum in C#
  • Convert an Object to JSON in C#
  • Convert JSON String to Object in C#
  • DateTime Formats in C#
  • How to convert date object to string in C#?
  • Compare strings in C#
  • How to count elements in C# array?
  • Difference between String and string in C#.
  • How to get a comma separated string from an array in C#?
  • Boxing and Unboxing in C#
  • How to convert string to int in C#?

await assignment c#

At tutorialsteacher.com, we are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in-depth, comprehensive, and easy to understand tutorials. We focus on a blend of theoretical explanations and practical examples to encourages hands-on learning. Learn more about us

  • Entrepreneur
  • Productivity

ConfigureAwait in .NET 8

I don’t often write “what’s new in .NET” posts, but .NET 8.0 has an interesting addition that I haven’t seen a lot of people talk about. ConfigureAwait is getting a pretty good overhaul/enhancement; let’s take a look!

ConfigureAwait(true) and ConfigureAwait(false)

First, let’s review the semantics and history of the original ConfigureAwait , which takes a boolean argument named continueOnCapturedContext .

When await acts on a task ( Task , Task<T> , ValueTask , or ValueTask<T> ), its default behavior is to capture a “context”; later, when the task completes, the async method resumes executing in that context. The “context” is SynchronizationContext.Current or TaskScheduler.Current (falling back on the thread pool context if none is provided). This default behavior of continuing on the captured context can be made explicit by using ConfigureAwait(continueOnCapturedContext: true) .

ConfigureAwait(continueOnCapturedContext: false) is useful if you don’t want to resume on that context. When using ConfigureAwait(false) , the async method resumes on any available thread pool thread.

The history of ConfigureAwait(false) is interesting (at least to me). Originally, the community recommended using ConfigureAwait(false) everywhere you could, unless you needed the context. This is the position I recommended in my Async Best Practices article . There were several discussions during that time frame over why the default was true , especially from frustrated library developers who had to use ConfigureAwait(false) a lot.

Over the years, though, the recommendation of “use ConfigureAwait(false) whenever you can” has been modified. The first (albeit minor) shift was instead of “use ConfigureAwait(false) whenever you can”, a simpler guideline arose: use ConfigureAwait(false) in library code and don’t use it in application code. This is an easier guideline to understand and follow. Still, the complaints about having to use ConfigureAwait(false) continued, with periodic requests to change the default on a project-wide level. These requests have always been rejected by the C# team for language consistency reasons.

More recently (specifically, since ASP.NET dropped their SynchronizationContext with ASP.NET Core and fixed all the places where sync-over-async was necessary), there has been a move away from ConfigureAwait(false) . As a library author, I fully understand how annoying it is to have ConfigureAwait(false) litter your codebase! Some library authors have just decided not to bother with ConfigureAwait(false) . For myself, I still use ConfigureAwait(false) in my libraries, but I understand the frustration.

An earlier version of this post incorrectly claimed that the Entity Framework Core team had decided not to use ConfigureAwait(false) . This was only true in early versions of Entity Framework Core. Entity Framework Core added ConfigureAwait(false) in version 5.0.0 and continues to use ConfigureAwait(false) as of this writing (2023-11-11).

Since we’re on the topic of ConfigureAwait(false) , I’d like to note a few common misconceptions:

  • ConfigureAwait(false) is not a good way to avoid deadlocks. That’s not its purpose, and it’s a questionable solution at best. In order to avoid deadlocks when doing direct blocking, you’d have to make sure all the asynchronous code uses ConfigureAwait(false) , including code in libraries and the runtime. It’s just not a very maintainable solution. There are better solutions available .
  • ConfigureAwait configures the await , not the task. E.g., the ConfigureAwait(false) in SomethingAsync().ConfigureAwait(false).GetAwaiter().GetResult() does exactly nothing. Similarly, the await in var task = SomethingAsync(); task.ConfigureAwait(false); await task; still continues on the captured context, completely ignoring the ConfigureAwait(false) . I’ve seen both of these mistakes over the years.
  • ConfigureAwait(false) does not mean “run the rest of this method on a thread pool thread” or “run the rest of this method on a different thread”. It only takes effect if the await yields control and then later resumes the async method. Specifically, await will not yield control if its task is already complete; in that case, the ConfigureAwait has no effect because the await continues synchronously.

OK, now that we’ve refreshed our understanding of ConfigureAwait(false) , let’s take a look at how ConfigureAwait is getting some enhancements in .NET 8. None of the existing behavior is changed; await without any ConfigureAwait at all still has the default behavior of ConfigureAwait(true) , and ConfigureAwait(false) still has the same behavior, too. But there’s a new ConfigureAwait coming into town!

ConfigureAwait(ConfigureAwaitOptions)

There are several new options available for ConfigureAwait . ConfigureAwaitOptions is a new type that provides all the different ways to configure awaitables:

First, a quick note: this is a Flags enum; any combination of these options can be used together.

The next thing I want to point out is that ConfigureAwait(ConfigureAwaitOptions) is only available on Task and Task<T> , at least for .NET 8. It wasn’t added to ValueTask / ValueTask<T> yet. It’s possible that a future release of .NET may add ConfigureAwait(ConfigureAwaitOptions) for value tasks, but as of now it’s only available on reference tasks, so you’ll need to call AsTask if you want to use these new options on value tasks.

Now, let’s consider each of these options in turn.

ConfigureAwaitOptions.None and ConfigureAwaitOptions.ContinueOnCapturedContext

These two are going to be pretty familiar, except with one twist.

ConfigureAwaitOptions.ContinueOnCapturedContext - as you might guess from the name - is the same as ConfigureAwait(continueOnCapturedContext: true) . In other words, the await will capture the context and resume executing the async method on that context.

ConfigureAwaitOptions.None is the same as ConfigureAwait(continueOnCapturedContext: false) . In other words, await will behave perfectly normally, except that it will not capture the context; assuming the await does yield (i.e, the task is not already complete), then the async method will resume executing on any available thread pool thread.

Here’s the twist: with the new options, the default is to not capture the context! Unless you explicitly include ContinueOnCapturedContext in your flags, the context will not be captured. Of course, the default behavior of await itself is unchanged: without any ConfigureAwait at all, await will behave as though ConfigureAwait(true) or ConfigureAwait(ConfigureAwaitOptions.ContinueOnCapturedContext) was used.

So, that’s something to keep in mind as you start using this new ConfigureAwaitOptions enum.

ConfigureAwaitOptions.SuppressThrowing

The SuppressThrowing flag suppresses exceptions that would otherwise occur when await ing a task. Under normal conditions, await will observe task exceptions by re-raising them at the point of the await . Normally, this is exactly the behavior you want, but there are some situations where you just want to wait for the task to complete and you don’t care whether it completes successfully or with an exception. SuppressThrowing allows you to wait for the completion of a task without observing its result.

I expect this will be most useful alongside cancellation. There are some cases where some code needs to cancel a task and then wait for the existing task to complete before starting a replacement task. SuppressThrowing would be useful in that scenario: the code can await with SuppressThrowing , and the method will continue when the task completes, whether it was successful, canceled, or finished with an exception.

If you await with the SuppressThrowing flag, then the exception is considered “observed”, so TaskScheduler.UnobservedTaskException is not raised. The assumption is that you are awaiting the task and deliberately discarding the exception, so it’s not considered unobserved.

There’s another consideration for this flag as well. When used with a plain Task , the semantics are clear: if the task faults, the exception is just ignored. However, the same semantics don’t quite work for Task<T> , because in that case the await expression needs to return a value (of type T ). It’s not clear what value of T would be appropriate to return in the case of an ignored exception, so the current behavior is to throw an ArgumentOutOfRangeException at runtime. To help catch this at compile time, a new warning was added : CA2261 The ConfigureAwaitOptions.SuppressThrowing is only supported with the non-generic Task . This rule defaults to a warning, but I’d suggest making it an error, since it will always fail at runtime.

As a final note, this is one flag that also affects synchronous blocking in addition to await . Specifically, you can call .GetAwaiter().GetResult() to block on the awaiter returned from ConfigureAwait . The SuppressThrowing flag will cause exceptions to be ignored whether using await or GetAwaiter().GetResult() . Previously, when ConfigureAwait only took a boolean parameter, you could say “ConfigureAwait configures the await”; but now you have to be more specific: “ConfigureAwait returns a configured awaitable”. And it is now possible that the configured awaitable modifies the behavior of blocking code in addition to the behavior of the await . ConfigureAwait is perhaps a slight misnomer now, but it is still primarily intended for configuring await . Of course, blocking on asynchronous code still isn’t recommended.

ConfigureAwaitOptions.ForceYielding

The final flag is the ForceYielding flag. I expect this flag will be rarely used, but when you need it, you need it!

ForceYielding is similar to Task.Yield . Yield returns a special awaitable that always claims to be not completed, but schedules its continuations immediately. What this means is that the await always acts asynchronously, yielding to its caller, and then the async method continues executing as soon as possible. The normal behavior for await is to check if its awaitable is complete, and if it is, then continue executing synchronously; ForceYielding prevents that synchronous behavior, forcing the await to behave asynchronously.

For myself, I find forcing asynchronous behavior most useful in unit testing. It can also be used to avoid stack dives in some cases. It may also be useful when implementing asynchronous coordination primitives, such as the ones in my AsyncEx library. Essentially, anywhere where you want to force await to behave asynchronously, you can use ForceYielding to accomplish that.

One point that I find interesting is that await with ForceYielding makes the await behave like it does in JavaScript. In JavaScript, await always yields, even if you pass it a resolved promise. In C#, you can now await a completed task with ForceYielding , and await will behave as though it’s not completed, just like JavaScript’s await .

Note that ForceYielding by itself also implies not continuing on the captured context, so it is the same as saying “schedule the rest of this method to the thread pool” or “switch to a thread pool thread”.

Task.Yield will resume on the captured context, so it’s not exactly like ForceYielding by itself. It’s actually like ForceYielding with ContinueOnCapturedContext .

Of course, the real value of ForceYielding is that it can be applied to any task at all. Previously, in the situations where yielding was required, you had to either add a separate await Task.Yield(); statement or create a custom awaitable. That’s no longer necessary now that ForceYielding can be applied to any task.

Further Reading

It’s great to see the .NET team still making improvements in async / await , all these years later!

If you’re interested in more of the history and design discussion behind ConfigureAwaitOptions , check out the pull request . At one point there was a ForceAsynchronousContinuation that was dropped before release. It had a more obscure use case, essentially overriding await ’s default behavior of scheduling the async method continuation with ExecuteSynchronously . Perhaps a future update will add that back in, or perhaps a future update will add ConfigureAwaitOptions support to value tasks. We’ll just have to see what the future holds!

await assignment c#

  • Async/await Intro
  • There Is No Thread
  • Don't Block on Async Code
  • React/Redux TodoMVC
  • A Tour of Task
  • Task.Run Etiquette
  • Task.Run vs. BackgroundWorker
  • TCP/IP .NET Sockets FAQ
  • Managed Services
  • IDisposable and Finalizers
  • Option Parsing

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Dot Net Tutorials

Async and Await in C#

Back to: C#.NET Tutorials For Beginners and Professionals

Async and Await in C# with Examples:

In this article, I am going to discuss how to implement Asynchronous Programming using Async and Await in C# with Examples. Please read our previous article where we discussed the basic concepts of Asynchronous and Parallel Programming .

Asynchronous Programming in C#:

Asynchronous programming allows us to have efficient applications where we do not waste resources when they are executed. In this article, we are going to discuss Asynchronous programming. Here, we will look at concepts and patterns for developing effective asynchronous applications. We will start by discussing async, await, and how we avoid freezing the UI. In the next article, we will see the use of Task, which represents a promise of a method of execution that will end in the future. We will talk about how to report Task progress, and how to cancel tasks, and we will also look at some patterns of asynchronous programming.

Async and Await Keyword in C#:

In modern C# code, in order to use asynchronous programming, we need to use async and await keywords. The idea is that if we have a method in which we want to use asynchronous programming, then we need to mark the method with the async keyword as shown in the below image.

Async and Await Operator in C#

For those asynchronous operations for which we do not want to block the execution thread i.e. the current thread, we can use the await operator as shown in the below image.

Asynchronous Programming in C#

So, when we use await operator, what we are doing is, we are freeing the current thread from having to wait for the execution of the task. In this way, we are avoiding blocking the current thread that we’re using and then that thread can be used in another task.

Async and await works in any .NET development environment like Console applications, Windows Form applications, ASP.NET Core for Web development, Blazor for interactive web applications, etc. Here, we are going to use a Console Application because it is really simple to use. But anything that we do in the Console Application will be applicable to any .NET development environment like ASP.NET Core.

Example to Understand Async and Await in C#:

Please have a look at the below example. It’s a very simple example. Inside the main method, first, we print that main method started, then we call the SomeMethod. Inside the SomeMethod, first, we print that SomeMethod started and then the thread execution is sleep for 10. After 10 seconds, it will wake up and execute the other statement inside the SomeMethod method. Then it will come back to the main method, where we called SomeMethod. And finally, it will execute the last print statement inside the main method.

When you execute the above code, you will see that after printing SomeMethod Started……, the console window is frozen for 10 seconds. This is because here we are not using asynchronous programming. One thread i.e. the Main thread is responsible for executing the code And when we call Thread.Sleep method the current thread is blocked for 10 seconds. This is a bad user experience.

Example to Understand Async and Await in C#

Now, let us see how we can overcome this problem by using asynchronous programming. Please have a look at the below image. The Thread.Sleep() is a synchronous method. So, we have changed this to Task.Delay() which is an asynchronous method. The Task.Delay() method exactly does the same thing as Thread.Sleep() does.

And, if we want to wait for the task i.e. Task.Delay to be done, then we have to use the await operator. As we said earlier the await operator is going to release the current thread that is running from having to wait for this operation. Therefore, that thread is going to be available for all our tasks. And then after 10 seconds, the thread will be called to the place (i.e. Task.Delay()) in order to run the rest code of the SomeMethod. As we have used await keyword inside the SomeMethod, we must have to make the SomeMethod as asynchronous as using the async keyword.

Asynchronous Programming using Async and Await Operators in C# with Examples

It is important to realize that await does not mean that the thread will have to be blocked waiting for the operation. Await means the thread is free to go to do another thing and then he will come back when this operation (in our example Task.Dealy i.e. after 10 seconds) is done. The following example code exactly does the same thing.

Asynchronous Programming using Async and Await Operators in C#

Now, if you run the above code, then you will see that after printing the Some Method Started when the statement Task.Dealy() executed, it will free the current thread, and then that current thread comes and execute the rest of the code inside the main method. And after 10 seconds again thread come back to the SomeMethod and execute the rest of the code inside the SomeMethod.

So, the bottom line is if you want to have a responsive UI that does not get blocked because of long-running operations, you must use asynchronous programming.

In the next article, I am going to discuss the Task Class in C# with Examples. Here, in this article, I try to explain how to implement Asynchronous Programming using Async and Await in C# with Examples. I hope you enjoy this Async and Await in C# with Examples article.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

10 thoughts on “Async and Await in C#”

await assignment c#

Guys, Please give your valuable feedback. And also, give your suggestions about this Async and Await Operator in C# concept. If you have any better examples, you can also put them in the comment section. If you have any key points related to Async and Await Operator in C#, you can also share the same.

await assignment c#

Interesting article

await assignment c#

well explained. Thank you

await assignment c#

Hi Sir, In the above code we have SomeMethod() and in that there is a line “await Task.Delay(TimeSpan.FromSeconds(10));”, as per this line the execution goes to main method to execute remaining lines of code. If suppose the remianing lines of code or logic in Main method, takes more than 10 seconds. How come the code/ threads will be handled and will SomeMethod() waits more than 10 seconds.

await assignment c#

Awesome explaination, any method that we think will do an asynchronous operation should be marked async, any time-consuming code inside the async method should be marked with await to free up thread & will come back to review if the awaited code has finished.

Can you do asynchronous operations that return data.

await assignment c#

/*In the above code we have SomeMethod() and in that there is a line “await Task.Delay(TimeSpan.FromSeconds(10));”, as per this line the execution goes to main method to execute remaining lines of code. If suppose the remianing lines of code or logic in Main method, takes more than 10 seconds. How come the code/ threads will be handled and will SomeMethod() waits more than 10 seconds.*/ No, the SomeMethod() won’t wait for some logic inside Main Method to finish. SomeMethod() will continue just ending the 10 seconds from “await Task.Delay(TimeSpan.FromSeconds(10));”

Try this code, I changed to 3 seconds the task.delay().

class Program { static void Main(string[] args) { Console.WriteLine(“Main Method Started……”); SomeMethod();

DateTime time1 = DateTime.Now; Console.WriteLine(“Starting Loop inside Main Method”);

for(int i=1 ; i <= 10000 ; i++) { for(int j =1; j <= 10000 ; j++) Console.Write("");

} Console.WriteLine("Ending Loop inside Main Method"); DateTime time2 = DateTime.Now; TimeSpan totaltime = time2-time1; Console.WriteLine($"Loop total time : {totaltime.TotalSeconds}");

Console.WriteLine("Main Method End"); Console.ReadKey(); } public async static void SomeMethod() { Console.WriteLine("Some Method Started……"); await Task.Delay(TimeSpan.FromSeconds(3)); //Console.WriteLine("\n"); Console.WriteLine("Some Method End"); } }

The output is:

Main Method Started…… Some Method Started…… Starting Loop inside Main Method Some Method End /* This is from SomeMethod() */ Ending Loop inside Main Method Loop total time : 5.398109 Main Method End

await assignment c#

That’s interesting post

await assignment c#

The reason why you get that behavior is fire & forget. You are calling async void method which is not awaited so Task.Delay that you are awaiting inside method is only awaited by the SomeMethod, but SomeMethod itself is not awaited so execution is continued

await assignment c#

Your article is very easy to read. Thanks you very much!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • async and await in C#

Dataward Promo

This tutorial will discuss Asynchronous programming in C#.

Asynchronous Programming in C#

If any process is blocked in a synchronous application, the whole application gets blocked and stops responding until that particular process gets completed. We can use asynchronous programming in this scenario. With asynchronous programming, our application can continue working in the background on some independent tasks until this particular process executes. In asynchronous programming, our whole application does not simply depend upon a single time-consuming process. Asynchronous programming is used with I/O bound or CPU bound tasks. The main use of asynchronous programming is to create a responsive User-Interface that does not get stuck while waiting for an I/O bound or CPU bound process to complete its execution. The await and async keywords are used for asynchronous programming in C#. The await keyword gives control back to the calling function. The await keyword is the main keyword that enables asynchronous programming in C#. The async keyword enables the await keyword. A function utilizing the await keyword must have the async keyword and return a Task object in C#. The await keyword cannot be used without the async keyword in C#. The following code example demonstrates synchronous programming in C#.

In the above code, the functions process1() and process2() are independent processes but the process2() function has to wait for the completion of the process1() function. This simple synchronous programming code can be converted to asynchronous programming with async and await keywords in C#.

In the above code, we used the async and await keywords to convert the previous example to asynchronous programming. The output clearly shows that the process2() function does not wait to complete the process1() function. In the definition of the process1() function, we used the async keyword to suggest that this is an Asynchronously executing function. The await keyword in the process1() function gives the control back to the main function, which then calls the process2() function. The control keeps shifting between the process1() and process2() functions until the completion of process1() function.

Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

C# Corner

  • TECHNOLOGIES
  • An Interview Question

C#

Async and Await in C#

await assignment c#

  • Vivek Kumar
  • May 15, 2023
  • Other Artcile

Basics of C# async await. In this article, you'll learn what C# async and C# await keywords are and how to use async and await in C# code.

Async and await keywords of C# were introduced in C# 5.0. They were designed to make it easier to write asynchronous code, which can run in the background while other code is executing.

The "async" keyword marks a method asynchronous, meaning it can be run in the background while another code executes. When you mark a method as async, you can use the "await" keyword to indicate that the method should wait for the result of an asynchronous operation before continuing.

Use of 'async' and 'await' in C#

Asynchronous programming is a programming technique that allows code to be executed concurrently without blocking the execution of the calling thread. In other words, asynchronous code can run in the background while other code is executing. In synchronous programming, each line of code is executed sequentially, and the program waits for each operation to complete before moving on to the next one. This can lead to performance problems, particularly in programs that need to perform long-running operations like I/O or network requests.

Asynchronous programming allows programs to perform these operations without blocking the calling thread. When an asynchronous operation is started, the program continues to execute other code while it waits for the operation to complete. The program is notified when the operation is complete and can continue with the following line of code.

Asynchronous programming can be implemented using various techniques, such as callbacks, events, and promises. In C#, the "async" and "await" keywords provide a convenient way to write asynchronous code that looks similar to synchronous code, making it easier to read and maintain.

We will get all the benefits of traditional Asynchronous programming with much less effort with the help of async and await keywords.

Suppose we are using two methods as, Method1 and Method2, respectively, and both methods are not dependent on each other, and Method1 takes a long time to complete its task. In Synchronous programming, it will execute the first Method1, wait for the completion of this method, and then execute Method2. Thus, it will be a time-intensive process even though both methods are not depending on each other.

We can run all the methods parallelly using simple thread programming, but it will block UI and wait to complete all the tasks. To come out of this problem, we have to write too many codes in traditional programming, but if we use the async and await keywords, we will get the solutions in much less code.

Also, we will see more examples, and if any third Method, as Method3 has a dependency on method1, it will wait for the completion of Method1 with the help of await keyword.

Async and await in C# are the code markers that mark code positions from where the control should resume after completing a task.

Let's start with practical examples for understanding the programming concept.

Code examples of C# async await 

We are going to take a console application for our demonstration.

In this example, we will take two methods that are not dependent on each other.

Code sample

In the code above, Method1 and Method2 are not dependent on each other, and we call from the Main method.

Here, we can see Method1 and Method2 are not waiting for each other.

await assignment c#

Regarding the second example, suppose we have Method3, which depends on Method1.

In this example, Method1 returns the total length as an integer value, and we pass a parameter as a length in Method3, which comes from Method1.

Here, we have to use await keyword before passing a parameter in Method3, and for it, we have to use the async keyword from the calling method.  

If we use C# 7 or less, we cannot use the async keyword in the Main method for the console Application because it will give the error below.  

await assignment c#

We will create a new method called callMethod, and in this method, we will call all our Methods Method1, Method2, and Method3, respectively.

Code sample   C# 7

Code sample C# 9

In the code above, Method3 requires one parameter, which is the return type of Method1. Here, the await keyword is vital in waiting for Method1 task completion.

await assignment c#

Real-time example

Some support APIs from the .NET Framework 4.5, and the Windows runtime contains methods that support async programming.

We can use all of these in the real-time project with the help of async and await keywords for the faster execution of the task.

Some APIs that contain async methods are HttpClient, SyndicationClient, StorageFile, StreamWriter, StreamReader, XmlReader, MediaCapture, BitmapEncoder, BitmapDecoder, etc.

In this example, we will read all the characters from a large text file asynchronously and get the total length of all the characters.

Sample code

In the code given above, we are calling a ReadFile method to read the contents of a text file and get the length of the total characters present in the text file.

In our sampleText.txt, the file contains too many characters, so It will take a long time to read all the characters.

Here, we are using async programming to read all the contents from the file, so it will not wait to get a return value from this method and execute the other lines of code. , However, it still has to wait for the line of code given below because we are using await keywords, and we will use the return value for the line of code below.

Subsequently, other lines of code will be executed sequentially. 

await assignment c#

Here, we must understand important points: if we are not using await keyword, then the method works synchronously. So the compiler will show the warning to us, but it will not show any error.

We can use async and await keywords in C# to implement async programming in this easy way,

If you're new to Async programming, here is a detailed tutorial  on Asynchronous programming in C# . 

  • Async In CSharp
  • Await In CSharp
  • CSharp Async
  • CSharp Await

C# Corner Ebook

Programming C# for Beginners

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

switch expression - pattern matching expressions using the switch keyword

  • 6 contributors

You use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression. For information about the switch statement that supports switch -like semantics in a statement context, see the switch statement section of the Selection statements article.

The following example demonstrates a switch expression, which converts values of an enum representing visual directions in an online map to the corresponding cardinal directions:

The preceding example shows the basic elements of a switch expression:

  • An expression followed by the switch keyword. In the preceding example, it's the direction method parameter.
  • The switch expression arms , separated by commas. Each switch expression arm contains a pattern , an optional case guard , the => token, and an expression .

At the preceding example, a switch expression uses the following patterns:

  • A constant pattern : to handle the defined values of the Direction enumeration.
  • A discard pattern : to handle any integer value that doesn't have the corresponding member of the Direction enumeration (for example, (Direction)10 ). That makes the switch expression exhaustive .

For information about the patterns supported by the switch expression and more examples, see Patterns .

The result of a switch expression is the value of the expression of the first switch expression arm whose pattern matches the input expression and whose case guard, if present, evaluates to true . The switch expression arms are evaluated in text order.

The compiler generates an error when a lower switch expression arm can't be chosen because a higher switch expression arm matches all its values.

Case guards

A pattern may be not expressive enough to specify the condition for the evaluation of an arm's expression. In such a case, you can use a case guard . A case guard is another condition that must be satisfied together with a matched pattern. A case guard must be a Boolean expression. You specify a case guard after the when keyword that follows a pattern, as the following example shows:

The preceding example uses property patterns with nested var patterns .

Non-exhaustive switch expressions

If none of a switch expression's patterns matches an input value, the runtime throws an exception. In .NET Core 3.0 and later versions, the exception is a System.Runtime.CompilerServices.SwitchExpressionException . In .NET Framework, the exception is an InvalidOperationException . In most cases, the compiler generates a warning if a switch expression doesn't handle all possible input values. List patterns don't generate a warning when all possible inputs aren't handled.

To guarantee that a switch expression handles all possible input values, provide a switch expression arm with a discard pattern .

C# language specification

For more information, see the switch expression section of the feature proposal note .

  • Use switch expression (style rule IDE0066)
  • Add missing cases to switch expression (style rule IDE0072)
  • C# reference
  • C# operators and expressions
  • Tutorial: Use pattern matching to build type-driven and data-driven algorithms
  • switch statement

.NET feedback

The .NET documentation is open source. Provide feedback here.

Submit and view feedback for

Additional resources

  • United States
  • United Kingdom

Joydip Kanjilal

By Joydip Kanjilal , Contributor, InfoWorld |

How to use IAsyncEnumerable in C#

Learn how to use iasyncenumerable in c# to easily filter, aggregate, transform, project, or otherwise process continuous streams of data asynchronously..

Queue, people waiting in line, async/await

IAsyncEnumerable is a powerful feature introduced in C# 8.0 that allows us to work with a sequence of data asynchronously. As the name suggests, IAsyncEnumerable is the asynchronous counterpart of IEnumerable, the interface that allows us to easily iterate through the elements of a collection.

Interestingly, the IAsyncEnumerable interface works on a pull-based approach, where the next item will either be created or retrieved when requested by the consumer. Unlike IEnumerable, which waits for the next element to be created, IAsyncEnumerable returns an awaitable that can be resumed later.

In this article, we will examine how we can use the IAsyncEnumerable interface in C# to work with asynchronous streams of data. 

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  • Launch the Visual Studio IDE.
  • Click on “Create new project.”
  • In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  • Click Next.
  • In the “Configure your new project” window, specify the name and location for the new project.
  • In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the Framework version you would like to use.
  • Click Create.

We’ll use this .NET 7 console application project to work with the code examples shown in the subsequent sections of this article.

IAsyncEnumerable benefits

The key benefits of IAsyncEnumerable include the following:

  • Support for asynchronous streaming: A traditional collection like a list or IEnumerable requires that all elements be available in advance. IAsyncEnumerable, on the other hand, streams items as they become available. Using IAsyncEnumerable is especially beneficial when dealing with large data sets or real-time data streams where all data may not be available in advance. With IAsyncEnumerable, you can start processing items immediately without having to wait for the data set to be loaded in its entirety. When working with real-time data feeds such as stock quotes or social media updates, where new information is constantly being generated and needs to be processed as soon as it is available, this flexibility is beneficial.
  • Efficient use of available resources: IAsyncEnumerable allows you to work with large sequences of data in an asynchronous manner, which ensures that valuable computing resources are not wasted.
  • Enhanced performance: IAsyncEnumerable can improve your application’s performance by eliminating the need to load all the data at one go. Consequently, the system can use less memory and free up resources. 
  • Improved responsiveness: With IAsyncEnumerable, you can easily write code that handles large streams of data responsively. You can also use resources more efficiently and improve overall application performance, so that your application remains responsive even when working with large data sets. 
  • Simpler code: IAsyncEnumerable simplifies code by eliminating complex synchronization mechanisms such as locks and semaphores thus reducing the likelihood of deadlocks and other synchronization-related issues in your application.

In the following section we’ll examine a few advanced operations you can perform on asynchronous sequences of data using IAsyncEnumerable.

Filtering with IAsyncEnumerable

The following code snippet illustrate how you can filter an asynchronous sequence of data to retrieve only the even numbers.

Aggregating with IAsyncEnumerable

The following code snippet illustrates how you can take advantage of IAsyncEnumerable to calculate the sum of integers in an asynchronous sequence of numbers.

Asynchronous projection with IAsyncEnumerable

The following code snippet shows how you can use projections with IAsyncEnumerable.

Transforming a sequence with IAsyncEnumerable

The following code snippet shows how you can take advantage of IAsyncEnumerable to transform a sequence of numbers and yield the transformed values.

Batch processing with IAsyncEnumerable

Apart from fetching items one at a time, you can also process items in batches when working with IAsyncEnumerable. This is shown in the code snippet given below.

What happened to the custom exception description I threw from a C++/WinRT IAsyncAction?

' data-src=

Raymond Chen

November 16th, 2023 0 1

A customer designed one of their methods such that it returns the answer on success, and on failure, it throws a Windows Runtime exception whose custom description is a JSON payload that describes what went wrong.

They found that sometimes the custom description they attached to the Windows Runtime exception was being truncated.

They wondered if maybe they should throw some other type of exception to encode the JSON information.

We learned a little while ago that the custom description associated with a Windows Runtime exception is a courtesy and may not survive transport across the ABI . In particular, the custom description is not intended for programmatic use. Its intended use is to inform the developer of additional information that may help diagnose the problem. For example, for an E_INVALIDARG failure, it may contain the name of the invalid parameter. But it’s not intended as a reliable side channel.

The Ro­Originate­Error function take a description for an about-to-be-returned failure and saves it in the per-thread side channel data. However, it saves only the first 250-ish characters of the message. I don’t know why it sets an artificial limit, but I have some ideas. For one thing, the description is already advisory anyway, and it’s supposed to be a brief message to help debug the problem. You weren’t expected to be passing large amounts of information, and perhaps the fixed limit is to prevent problems if somebody decides to pass a 1 gigabyte string as an “error description”.

At any rate, you can’t put functionally significant information in the error description because it may not even survive at all.

What the component should do is report the JSON error message as part of a compound return value.

We can then use this Item­Name­Result as the return value of Get­Item­Name­Async .

' data-src=

Leave a comment Cancel reply

Log in to join the discussion.

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

IMAGES

  1. Async and Await in C# with Examples

    await assignment c#

  2. Task & Async Await C#

    await assignment c#

  3. Async Await In C#

    await assignment c#

  4. Await in a catch and finally Block in C# 6.0

    await assignment c#

  5. Async And Await In C#

    await assignment c#

  6. Async and Await C# and Visual Basic

    await assignment c#

VIDEO

  1. making a game pt30

  2. [C#] Async/Await

  3. Unity C#

  4. 2- Course C# Resala

  5. C# Multithreading Task/Async/Await Part 2: C# Code

  6. RedditLite

COMMENTS

  1. C#

    2 Answers Sorted by: 1 Here's one possible implementation, assuming you want to StartClient on all bots sequentially and then call setConnection and await them all to finish.

  2. await operator

    C# language specification See also The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.

  3. The Task Asynchronous Programming (TAP) model with async and await'

    The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in .NET Framework, .NET Core, or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method.

  4. How Async/Await Really Works in C#

    // Synchronously copy all data from source to destination. public void CopyStreamToStream(Stream source, Stream destination) { var buffer = new byte[0x1000]; int numRead; while ( (numRead = source.Read(buffer, 0, buffer.Length)) != 0) { destination.Write(buffer, 0, numRead); } }

  5. Asynchronous programming scenarios

    The await keyword is where the magic happens. It yields control to the caller of the method that performed await, and it ultimately allows a UI to be responsive or a service to be elastic. While there are ways to approach async code other than async and await, this article focuses on the language-level constructs. Note

  6. Asynchronous programming with async, await, Task in C#

    28 Jan 2022 C# and .NET Framework (4.5 & Core) supports asynchronous programming using some native functions, classes, and reserved keywords. Before we see what is asynchronous programming, let's understand what is synchronous programming using the following console example. Example: Asynchronous Program

  7. ConfigureAwait in .NET 8

    First, let's review the semantics and history of the original ConfigureAwait, which takes a boolean argument named continueOnCapturedContext. When await acts on a task ( Task, Task<T>, ValueTask, or ValueTask<T> ), its default behavior is to capture a "context"; later, when the task completes, the async method resumes executing in that ...

  8. Understanding Control Flow with Async and Await in C#

    In the previous guide in this series we took a look at the basics of the async and await keywords in C#. Once you get the hang of their syntax and usage, it can actually be quite a joy to write asynchronous code. In fact, it feels so natural that one can forget that the code is asynchronous! Often this is an advantage; you can ignore the ...

  9. await operator

    \n\n await operator - asynchronously await for a task to complete \n. The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any. When the await operator is applied to the operand that represents an already ...

  10. Discards

    C# (_, _, area) = city.GetCityInformation (cityName); Beginning with C# 9.0, you can use discards to specify unused input parameters of a lambda expression. For more information, see the Input parameters of a lambda expression section of the Lambda expressions article.

  11. c#

    public static async Task dosthA () { //This will be working synchronously, take 3 seconds. await sleep (); await sleep (); await sleep (); //This will be working asynchronously, take 1 second only. Task A = sleep (); Task B = sleep (); Task C = sleep (); await A; await B; await C; }

  12. C# Tutorial: Getting Started with Async and Await

    In C#, using async and await is the primary way of doing such asynchronous waiting, and this guide will help you get started with that. But as mentioned in the previous guide in this series, it is possible to do asynchronous programming in C# without these keywords. So why were these keywords introduced, and why are they so important?

  13. c#

    What happens is that the assignment to department and everything following the await keyword get boxed into a closure and for all intents and purposes passed to the Task.ContinueWith method (the FindAsync function is automatically executed on a different thread).

  14. c#

    2 Answers. Sorted by: 3. You should also mark you event handler as async. private async Task button1_Click (object sender, EventArgs e) and await instead of Wait: private async Task button1_Click (object sender, EventArgs e) { await getData (); Console.WriteLine ("Step 3"); } When we use the async/await pattern, we should go this way until the ...

  15. .net

    1 This program does not print the output in the correct order. public static void Main (string [] args) { new Program ().Start (); } public async void Start () { int num1 = await GetNumber (); int num2 = await GetNumber (); int num3 = await GetNumber (); Console.WriteLine ("Wait...");

  16. Async and Await in C# with Examples

    Async and Await Keyword in C#: In modern C# code, in order to use asynchronous programming, we need to use async and await keywords. The idea is that if we have a method in which we want to use asynchronous programming, then we need to mark the method with the async keyword as shown in the below image. For those asynchronous operations for ...

  17. async and await in C#

    The await keyword gives control back to the calling function. The await keyword is the main keyword that enables asynchronous programming in C#. The async keyword enables the await keyword. A function utilizing the await keyword must have the async keyword and return a Task object in C#. The await keyword cannot be used without the async ...

  18. Async and Await in C#

    In C#, the "async" and "await" keywords provide a convenient way to write asynchronous code that looks similar to synchronous code, making it easier to read and maintain. We will get all the benefits of traditional Asynchronous programming with much less effort with the help of async and await keywords.

  19. c#

    The whole point of await is that it allows you to handle asynchronous code as if it were synchronous. So from the outside, it appears as if you never left the method until you actually get to a return (or the end of the method). For this to work, however, your method must return a Task (or Task<T>), and the callee must await your method in turn.

  20. switch expression

    In this article. You use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression. For information about the switch statement that supports switch-like semantics in a statement context, see the switch statement section of the Selection statements article.. The following example demonstrates a switch expression ...

  21. How to use IAsyncEnumerable in C#

    The following code snippet shows how you can take advantage of IAsyncEnumerable to transform a sequence of numbers and yield the transformed values. public async IAsyncEnumerable<string ...

  22. Email via C# not sending without Console.ReadLine

    I have a routine that I found that sends emails from a Windows server. This is basically the code that I'm trying to figure out: // Set the method that is called back when the send operation ends. client.SendCompleted += new SendCompletedEventHandler (SendCompletedCallback); // The userState can be any object that allows your callback // method ...

  23. Semantic Kernel's Ignite release: Beta8 for the .NET SDK

    Gen-5: With Stepwise planner v2, leverage the best of OpenAI.. The other big advancement from OpenAI has been the improvements to function calling.With function calling, OpenAI models are much better at picking the right function and invoking it with the correct arguments. During our Beta6 release, we completed our integration with function calling which allowed us to bake it into our updated ...

  24. What happened to the custom exception description I threw from a C++

    A customer designed one of their methods such that it returns the answer on success, and on failure, it throws a Windows Runtime exception whose custom description is a JSON payload that describes what went wrong.