RingDotNetfor Ring

Tasks that wait

A Task is something that finishes later. .NET can start many of them at once, wait for all or for the first, give up after a time limit, and cancel the ones that are no longer needed. This lesson uses delays to show it, without any threads of your own.

What you will learn#

Tasks and Ring#

In .NET a task is a promise: a piece of work that is running or waiting and will be finished, failed or canceled. HttpClient.GetAsync, File.ReadAllTextAsync and Process.WaitForExitAsync all return tasks. Ring runs your code on one thread, and Ring code cannot run on other threads (Core concepts), so you do not write the work of a task in Ring. You use the tasks that .NET provides, start several, and wait for them in Ring. Task.Delay is the simplest such task: it finishes after a time and does nothing else, which makes the rules visible.

The program#

samples/UsingDotNet/tutorials/ch06_tasks_waiting.ring
# tasks that wait - Task.Delay, WhenAll, WhenAny, time limits and cancellation (System.Threading.Tasks)
load "dotnet.ring"

using {
	"System"
	"System.Diagnostics"
	"System.Threading"
	"System.Threading.Tasks"
}

func main

	oTasks = new Task()

	# 1. A Task is "something that finishes later". Task.Delay(ms) is a task that finishes after that time, without using a thread to sleep.
	oWatch = new Stopwatch()
	oWatch.Start()
	oOne = oTasks.Delay(300)
	? "1. the task was made at once (under 100 ms): " + yesNo(oWatch.ElapsedMilliseconds < 100) + ", finished already? " + yesNo(oOne.IsCompleted)
	oOne.Wait(NULL)
	? "   after Wait it is finished (" + oOne.Status + ") and about 300 ms have passed: " + yesNo(oWatch.ElapsedMilliseconds >= 280)

	# 2. WhenAll: one task that finishes when ALL of them did. Three waits of 300 ms together take about 300 ms, not 900.
	oWatch.Restart()
	oAll = oTasks.WhenAll([oTasks.Delay(300),oTasks.Delay(300),oTasks.Delay(300)])
	oAll.Wait(NULL)
	nAll = oWatch.ElapsedMilliseconds
	? nl + "2. three waits of 300 ms, started together, took less than 700 ms: " + yesNo(nAll < 700) + " (and at least 300: " + yesNo(nAll >= 280) + ")"

	# 3. WhenAny: finishes when the FIRST one does. The task that finished is the result.
	oFast = oTasks.Delay(100)
	oSlow = oTasks.Delay(1000)
	oFirst = oTasks.WhenAny([oSlow,oFast])
	oFirst.Wait(NULL)
	? nl + "3. WhenAny finished when the fast task did: fast is done " + yesNo(oFast.IsCompleted) + ", slow is done " + yesNo(oSlow.IsCompleted)

	# 4. A time limit: Wait(ms) gives up after that time and answers false when the task is not finished
	oLong = oTasks.Delay(2000)
	lDone = oLong.Wait(200)
	? nl + "4. waited 200 ms for a task of 2 seconds: finished = " + yesNo(lDone) + " (the task keeps running; you stopped waiting)"

	# 5. Cancellation: a CancellationTokenSource says "stop". CancelAfter(ms) says it later. A task that got the token ends as canceled.
	oSource = new CancellationTokenSource()
	oSource.CancelAfter(100)
	oCancellable = oTasks.Delay([ :millisecondsDelay = 5000, :cancellationToken = oSource.Token ])
	lError = False
	try
		oCancellable.Wait(NULL)
	catch
		lError = True
	done
	? nl + "5. a delay of 5 seconds canceled after 100 ms: the wait raised an error " + yesNo(lError) + ", the task is canceled: " + yesNo(oCancellable.IsCanceled) + ", status " + oCancellable.Status
	oSource.Dispose()

	# 6. Many waits, one result: wait for all pages of a list (here: delays standing for downloads) and see that they ran together
	aDelays = [50,120,80,200,30]
	aList = []
	for nDelay in aDelays
		aList + oTasks.Delay(nDelay)
	next
	oWatch.Restart()
	oTasks.WhenAll(aList).Wait(NULL)
	nTotal = 0
	for nDelay in aDelays
		nTotal += nDelay
	next
	? nl + "6. five waits that add up to " + nTotal + " ms were over in less than that: " + yesNo(oWatch.ElapsedMilliseconds < nTotal)

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. the task was made at once (under 100 ms): yes, finished already? no
   after Wait it is finished (RanToCompletion) and about 300 ms have passed: yes

2. three waits of 300 ms, started together, took less than 700 ms: yes (and at least 300: yes)

3. WhenAny finished when the fast task did: fast is done yes, slow is done no

4. waited 200 ms for a task of 2 seconds: finished = no (the task keeps running; you stopped waiting)

5. a delay of 5 seconds canceled after 100 ms: the wait raised an error yes, the task is canceled: yes, status Canceled

6. five waits that add up to 480 ms were over in less than that: yes

The output prints yes and no instead of the exact milliseconds, so that it is the same on every computer. When you try it yourself, print ElapsedMilliseconds.

How it works#

Delay and Wait#

Task.Delay(300) returns at once with a task that is not finished yet (IsCompleted is false). Wait(NULL) blocks the Ring program until the task is finished; its Status is then RanToCompletion. Making the task and waiting for it are two separate steps — that separation is what lets you start many tasks first.

WhenAll and WhenAny#

Task.WhenAll([t1, t2, t3]) is a new task that finishes when all of them did. Three delays of 300 ms started together are over after about 300 ms, not 900. The same idea turns a hundred slow downloads into one wait. Task.WhenAny([…]) finishes with the first one: here the fast delay finishes and the slow one is still running.

The tasks go into a Ring list, which WhenAll and WhenAny take as an array of tasks.

A time limit#

oTask.Wait(200) waits at most 200 ms and answers true if the task finished, false if the time ran out. The task keeps running; you only stopped waiting. Use it so that a missing server cannot block your program for ever; Wait(NULL) waits without a limit.

Cancellation#

A CancellationTokenSource is a switch. CancelAfter(100) turns it on after 100 ms. Its Token goes with the work: Task.Delay([ :millisecondsDelay = 5000, :cancellationToken = oSource.Token ]) is a delay of five seconds that ends canceled when the switch turns on. Waiting for a canceled task raises an error (the catch sees it), IsCanceled is true and Status is Canceled. Most asynchronous methods of .NET accept a token as their last parameter, for example HttpClient.GetAsync (the tutorial HttpClient in depth).

Tip

Dispose a CancellationTokenSource when you are done with it (oSource.Dispose()).

Many waits, one result#

Step 6 starts five delays and waits for them with one WhenAll: the total is about 200 ms (the longest), not the 480 ms that they add up to.

What you learned#

Exercises#

  1. Start three HttpClient requests (the tutorial HttpClient in depth) and wait for all with WhenAll; compare the time with doing them one after another.
  2. Print the elapsed milliseconds for each step and see how close they are to the delays.
  3. Use WhenAny with a delay as a timeout: whichever of a request and a 2-second delay ends first wins.
  4. Cancel a Process.WaitForExitAsync of a program that runs for a minute.

Next#

Releasing resources

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.