Time, tasks and other programs
Measure how long something takes, wait for background work, read the environment, and run another program and read what it prints.
What you will learn#
Stopwatchto measure time,- tasks and
Wait, Environment: the computer and its variables,Process: start another program,- the one important rule about threads.
The program#
# time, tasks and other programs - Stopwatch, Task, Process, Environment
load "dotnet.ring"
using {
"System"
"System.Diagnostics"
"System.Threading.Tasks"
"System.Threading"
}
func main
# Measuring time: Stopwatch
oWatch = new Stopwatch()
oWatch.Start()
new Thread().Sleep(120)
oWatch.Stop()
? "Slept about 120 ms, measured at least 100: " + (oWatch.ElapsedMilliseconds >= 100)
# Tasks run work in the background; Wait() waits for the end on the Ring thread
oTask = new Task().Delay(100)
? "Task finished at once? : " + oTask.IsCompleted
oTask.Wait(NULL)
? "Task finished after Wait : " + oTask.IsCompleted
# A task that has a result
oResult = new Task().FromResult("done")
? "Task result : " + oResult.Result
# The environment
oEnvironment = new Environment()
? nl + "Machine name : " + (len(oEnvironment.MachineName) > 0)
? "Number of processors : " + (oEnvironment.ProcessorCount >= 1)
? "A variable (PATH) exists : " + (len(oEnvironment.GetEnvironmentVariable("PATH")) > 0)
? "Current folder is known : " + (len(oEnvironment.CurrentDirectory) > 0)
# Running another program and reading what it prints
cShell = "sh"
cShellOption = "-c"
if isWindows()
cShell = "cmd"
cShellOption = "/c"
ok
oInfo = new ProcessStartInfo() {
FileName = cShell # cmd /c on Windows, sh -c on Linux and macOS
Arguments = cShellOption + ' "echo hello from another program"'
RedirectStandardOutput = True
UseShellExecute = False
CreateNoWindow = True
}
oProcess = new Process().Start([ :startInfo = oInfo ])
cOutput = oProcess.StandardOutput.ReadToEnd()
oProcess.WaitForExit(NULL)
? nl + "The other program said: " + trim(cOutput)
? "Its exit code : " + oProcess.ExitCode
# Important: Ring code runs on ONE thread. A task is good for waiting or for pure .NET work.
# A callback that .NET runs on another thread can not call Ring (see 'Rules and limits').Slept about 120 ms, measured at least 100: 1
Task finished at once? : 0
Task finished after Wait : 1
Task result : done
Machine name : 1
Number of processors : 1
A variable (PATH) exists : 1
Current folder is known : 1
The other program said: hello from another program
Its exit code : 0How it works#
Stopwatch#
Start(), Stop(), then ElapsedMilliseconds (or Elapsed for a TimeSpan). Thread.Sleep(120) pauses the program for 120 ms. Measure the parts of a program that feel slow before you try to speed anything up.
Tasks#
A Task represents work that happens "in the background" or in the future. Task.Delay(100) is a task that completes after 100 ms. IsCompleted says whether it is done; Wait(NULL) blocks until it is. Task.FromResult("done") is a task that is already finished, with the result done, read with its property Result.
The rule: Ring runs on one thread#
.NET can do many things at once on many threads. Ring code runs on one thread only. A callback that .NET wants to start from another thread has to be handed to the Ring thread: the web server does it with serveOne() (see HTTP), and the timers of Windows Forms (uiTimer) already tick on the Ring thread. So use tasks for waiting and for pure .NET work (HTTP, files, hashing), and keep your Ring code on the Ring thread.
The environment#
Environment knows the computer: MachineName, ProcessorCount, CurrentDirectory, GetEnvironmentVariable("PATH"), UserName, OSVersion. The program prints only true for each, so that the output is the same on every computer.
Running another program#
ProcessStartInfo describes what to run: FileName, Arguments, and:
| Property | Meaning |
|---|---|
RedirectStandardOutput = True | you read what the program prints |
UseShellExecute = False | run it directly (needed to redirect) |
CreateNoWindow = True | no console window |
Process.Start([ :startInfo = oInfo ]) starts it; StandardOutput.ReadToEnd() reads all its output; WaitForExit(NULL) waits for the end; ExitCode is 0 when the program succeeded.
The program starts the shell of the system with a command: cmd /c "echo ..." on Windows and sh -c "echo ..." on Linux and macOS (isWindows() chooses). This is how a Ring program uses any command-line tool: git, ping, ffmpeg, dotnet.
What you learned#
- time measuring and waiting,
- tasks and their results,
- the Ring-thread rule,
- the environment and starting other programs.
Exercises#
- Measure how long it takes to compute 100000 square roots in a Ring loop.
- Run
cmd /c dir(sh -c lson Linux and macOS) and count the lines in its output. - Print the three biggest environment variables by length (
GetEnvironmentVariables()). - Start
notepad.exe(on Windows) with aProcess, wait 3 seconds and close it withKill().
Where to go next#
This was the last tutorial of the chapter The basics. The next chapter is Text and data formats: it starts with Regular expressions in depth. The Tutorials page lists all the chapters, and you can start any of them.