twinbasic / lang-design

Language Design for twinBASIC
MIT License
11 stars 1 forks source link

Discussion: Asynchrony #20

Open mansellan opened 3 years ago

mansellan commented 3 years ago

Is your feature request related to a problem? Please describe. Asynchronous programming doesn't always require a programmer to think in terms of multiple threads. .Net's async\await is an object lesson in making difficult things seem simple.

Describe the solution you'd like Consider the following method:

Public Sub UpdateDatabase(CustomerId As Integer)
  On Error Goto DatabaseError

  _connection.Execute("UPDATE MyTable SET IsActive = 1 WHERE CustomerId = @p1", CustomerId)

DatabaseError:
  Msgbox "Failed"
End Sub

This is a synchronous call which will block the thread until the database responds. We could solve this by offloading to a background thread, but then we have to worry about thread synchronisation, exception marshalling, and protecting shared-state variables.

The async\await apparatus in .Net allows us to write async code in a very similar style to synchronous code:

Public Async Function UpdateDatabase(CustomerId As Integer) As Task
  On Error Goto DatabaseError

  Await _connection.Execute("UPDATE MyTable SET IsActive = 1 WHERE CustomerId = @p1", CustomerId)

DatabaseError:
  Msgbox "Failed"
End Sub

Describe alternatives you've considered Multi-threading can definitely achieve asynchrony, but it's kinda a sledgehammer to crack a nut when all you want to do is to carry on whilst you wait for an I/O operation to complete.

Additional context Async/Await is a classic example of making difficult things appear to be simple. I suspect Microsoft invested millions in making it work; it may be impossible for twinBASIC to replicate. For example, Awaiting inside of a loop requires the .Net compiler to rewrite sections of your code as a state machine. I may be asking for the moon here.

sancarn commented 2 years ago

Interestingly there is a way to have a COM complient asynchronous interface which coincidentally was recently discussed by Raymond Chen