Callbacks and events
Many .NET methods ask you for a piece of code: how to compare, which items to keep, what to do when something happens. This lesson shows the three ways to give Ring code to .NET and the rules that keep it working.
What you will learn#
- what a callback (a delegate) is,
- the three ways to write one: a function name, a text of code, an event handler,
- the argument and result convention:
aDotNetArgsandxDotNetResult, - what happens with errors inside a callback,
- why callbacks must run on the Ring thread.
What is a callback?#
Sometimes a .NET method does not know what exactly to do:
| Method | The part it does not know |
|---|---|
List.Sort | how to compare two items |
List.FindAll | which items to keep |
List.ForEach | what to do with each item |
an event such as Click | what to do when it happens |
You give it a callback: code that .NET calls back when it needs the answer. In .NET the type of such a thing is a delegate (Action, Func, Predicate, Comparison, EventHandler...). In Ring you create one with dnCallback(...).
The program#
# callbacks and events - giving Ring code to .NET
load "dotnet.ring"
using {
"System.Collections.Generic"
"System.Collections.ObjectModel"
"System.Collections.Specialized"
}
# Callback code can only see global variables
nLetters = 0
nChanges = 0
func main
oWords = new StringList()
oWords.Add("pear") oWords.Add("apple") oWords.Add("fig") oWords.Add("avocado")
# 1. A callback that is the NAME of a function. .NET calls it once for each item.
? "1. ForEach calls showItem for every word:"
oWords.@ForEach(dnCallback("showItem"))
# 2. A callback that decides: sort with your own comparison
oWords.Sort([ :comparison = dnCallback("compareLength") ])
? nl + "2. Sorted by length: " + joinList(oWords.toList())
# 3. A callback that answers yes or no: find the words that start with a
oFound = oWords.FindAll(dnCallback("startsWithA"))
? "3. Words starting with a: " + joinList(oFound.toList())
? " Does 'fig' exist? : " + oWords.Exists(dnCallback("isFig"))
# 4. A callback that is a piece of CODE in a text. aDotNetArgs holds the arguments, xDotNetResult is the answer
oWords.@ForEach(dnCallback("nLetters += len(aDotNetArgs[1])"))
? "4. Total letters: " + nLetters
oWords.Sort([ :comparison = dnCallback("xDotNetResult = len(aDotNetArgs[2]) - len(aDotNetArgs[1])") ])
? " Longest word : " + oWords.Item(0)
# 5. An EVENT: .NET calls your code when something happens
oList = new ObservableStringList()
oList.setCollectionChangedEvent("nChanges++ ? ' event ' + nChanges + ': ' + aDotNetArgs[2].Action")
? nl + "5. Changing an observable list:"
oList.Add("one")
oList.Add("two")
oList.RemoveAt(0)
? " events received: " + nChanges
oList.clearCollectionChangedEvent()
oList.Add("three")
? " after clearing the handler, still " + nChanges
# 6. An error inside a callback comes out of the .NET method that called it
try
oWords.@ForEach(dnCallback("broken"))
catch
? nl + "6. Caught: " + cCatchError
done
# A callback written as a function receives ONE parameter: the list of the .NET arguments. It returns the answer.
func showItem aArgs
? " item: " + aArgs[1]
func compareLength aArgs
return len(aArgs[1]) - len(aArgs[2])
func startsWithA aArgs
return left(aArgs[1],1) = "a"
func isFig aArgs
return aArgs[1] = "fig"
func broken aArgs
raise("the callback failed on purpose")
func joinList aList
cText = ""
for xItem in aList
if cText != ""
cText += ", "
ok
cText += xItem
next
return cText1. ForEach calls showItem for every word:
item: pear
item: apple
item: fig
item: avocado
2. Sorted by length: fig, pear, apple, avocado
3. Words starting with a: apple, avocado
Does 'fig' exist? : 1
4. Total letters: 19
Longest word : avocado
5. Changing an observable list:
event 1: Add
event 2: Add
event 3: Remove
events received: 3
after clearing the handler, still 3
6. Caught: DotNet Error: System.InvalidOperationException: Ring error: the callback failed on purposeThis program uses a generic function (getProp) where a class cannot be used. The lesson The generic functions explains them.
How it works#
1. A function name#
dnCallback("showItem") is the simplest form: the name of a Ring function. .NET calls it once per item. The function gets one parameter, a list of the arguments that .NET passes, and returns the result:
func showItem aArgs
? " item: " + aArgs[1]@ForEach starts with @ because ForEach is a Ring keyword.
2. A callback that decides#
Sort([ :comparison = dnCallback("compareLength") ]) passes a comparison. .NET gives the function two items (aArgs[1], aArgs[2]); it returns a negative number if the first goes first, a positive one if the second goes first, and 0 for equal. Subtracting the lengths does exactly that: fig, pear, apple, avocado.
FindAll and Exists take a predicate: a function that returns true or false for an item.
3. A piece of code in a text#
If the text is not just a function name, it is Ring code. It reads the arguments in aDotNetArgs and writes its answer into xDotNetResult:
oWords.@ForEach(dnCallback("nLetters += len(aDotNetArgs[1])"))
oWords.Sort([ :comparison = dnCallback("xDotNetResult = len(aDotNetArgs[2]) - len(aDotNetArgs[1])") ])This is handy for one-liners. The code is compiled once, the first time, so using it in a loop costs nothing extra.
4. Events#
An event is a delegate that .NET stores and calls later, possibly many times. setCollectionChangedEvent("code") sets the handler of the event CollectionChanged; clearCollectionChangedEvent() removes it. The code gets aDotNetArgs = [sender, eventArgs]: aDotNetArgs[2].getProp('Action') says what happened (Add, Remove). After the handler was cleared, the third change raised no event.
The same works for every event of every class: a button's Click, a text box's TextChanged, a form's FormClosing.
5. Errors#
An error raised inside a callback (raise(...)) travels back through .NET and comes out of the method that called it, so your try / catch around @ForEach catches it.
The rules#
Code in a callback sees only global variables. It runs later, outside the function that created it. nLetters and nChanges are global in the program. A local variable of main would be unknown to the callback.
Callbacks run on the Ring thread, during a call. A callback that .NET invokes from another thread (a thread-pool timer, a task) is not run; a message is written on stderr. Use Windows Forms timers (uiTimer) for repeating work, and wait for tasks on the Ring thread.
What you learned#
| Idea | Example |
|---|---|
| a callback by function name | dnCallback("showItem") |
| arguments and result | aArgs[1], return |
| code in a text | aDotNetArgs[1], xDotNetResult |
| an event | setCollectionChangedEvent("..."), clear...Event() |
| errors travel back | try around the .NET call |
Exercises#
- Sort the words alphabetically by their last letter.
- Use
FindAllto keep the words with more than four letters, and@ForEachto print them in upper case. - Make a handler for
CollectionChangedthat prints the new item (aDotNetArgs[2].getProp('NewItems')). - Set the same event twice and see that the second handler replaces the first.