Skip to content

Use the Task-based asynchonous model#4

Open
JesHansen wants to merge 4 commits intomakeratplay:mainfrom
JesHansen:use-tap-model
Open

Use the Task-based asynchonous model#4
JesHansen wants to merge 4 commits intomakeratplay:mainfrom
JesHansen:use-tap-model

Conversation

@JesHansen
Copy link
Contributor

Fixes #3

In this PR I've switched the asynchronous pattern from the old BeginX/EndX to the more modern Task-based API. The PR consists of a number of small commits so that it's easier to follow along. The PR consists of the following logical steps:

  • Upgrade the .NET framework to allow using the Task-based API for sockets.
  • Refactor the StartListening method. The method was doing multiple things, these have been separated out into their own, smaller methods. The overall flow is still the same, but it's easier to get an overview of that the code is doing, due to the smaller method sizes.
  • Refactor from using the BeginReceive/EndReceive pattern to using a Task for the purpose. This change is contained in its own commit to make it clear what parts I changed to implement this.

The logic behind how packets are processed is simpler as the async parts are now in a central place, instead of being spread across multiple methods. This allows us to use a simpler mental model of what is happening: Loop to receive packets, handle them as they arrive, shut down when the socket is closed.

I've tested that the app still runs, but async code is tricky; there could easily be something I've overlooked. Do test thouroughly before merging anyhing from the latest commit in this PR. Please let me know if you can spot any behaviour that changes due to this PR. :-)

To use the Task based model for asynchronous communication, we need to update the framework version, so that we have access to the Task-based API for Sockets.
The StartListening method does three things: Sets up a localIP address, configures a socket, and start the listening. This change extracts the local IP setup into it's own method.
The Task based model enables us to use a more natural way to reason
about the asynchronous part of the program. Previously the async parts
were being done in two places, now all the async parts are in one place.

The logic is also easier to grok: Listening for packets is done by
looping around, parsing received data and exiting the loop once the
socket is disposed.
Copy link
Owner

@makeratplay makeratplay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry it took so long to review this PR, but you know life happens. Changes look good to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use of depricated asynchronous pattern

2 participants