.Net CoreC#Development

C#: From Event-based Asynchronous Pattern to Task-based Asynchronous Pattern

Task-based Asynchronous Pattern (TAP) was introduced in .NET Framework 4 and since then, it is the recommended approach to asynchronous programming in .NET. Based on System.Threading.Tasks.Task and async and await keywords/operators to handle asynchronous programming in C#.

Even more, newest C# code is more or less all over “populated” with async/await(s). Hence, If you write modern C# code, you definitively already stumbled at async/await.

On the other hand, older Event-based Asynchronous Pattern (EAP) is still in use, especially at legacy systems, but for new development is not recommended anymore. The idea behind EAP is to register to event and wait for the callback from processing/asynchronous code.

In this blog post I will show how to “migrate” from EAP to TAP pattern on a simple example. Of course, asynchronous programming is broad topic, here I will just cover simple – but the most generic case – how to switch from EAP to TAP.

EAP Example

Lets look at this simple code:

Logic here is very simple: EventBasedTriggerManager triggers event after some timeout upon Start() is called. I can register to this event and get callback when action is invoked. To be more illustrative, let’s check next code:

My super awesome app returns this:

Everything clear here: I registered my event handler to wait for event to get triggered. It would be super awesome, if I could rewrite this as async/await. So, let’s get our hands dirty.

TAP Example (wrapper)

The idea is to wrap upper EAP code into TAP.

My calling code is now rewritten into:

You can see async call to Task based function trigger.StartAsync(), and the result is like this:

But what happens when async gets out of timeout! Let’s reduce timeout to 2 sec (trigger is executed after 5 sec, by default). I just changed TimeSpanin CancelAfter() method on CancellationTokenSource object, e.g.

The output is as expected, I get timeout.

Voila, we have it: simple EAP to TBP wrapper.

Conclusion

I shared simple example how to rewrite/wrap event-based asynchronous code to task-based asynchronous approach. It’s not silver bullet, but in many cases you can use similar approach.

If you have similar problems/solutions give me a ping and share your ideas.

Happy coding!

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.