Recently, I need to read the data from a code scanner, which is recognized as a keyboard, in the dotnet program development of Linux. Because the program is running background, hosted in systemd, there is no way to get the entered text from console. All devices are presented as files in Linux. Reading the event from keyboard device file /dev/input/eventX is a good choice.
To read from the device in Linux, FileStream need to be created on the device file. Using the method Read() form the instance of FileStream, all key events can be processed one by one. For make it easy, I post the code in GitHub. Nuget package is also presented.
The sad thing is, there is no way to stop the FileStream.Read method except quit the app. The Read method is designed to read at least one byte. If there is no data available currently but not reaching the end of file, it will block and wait. And there is no way to break the waiting. I also tried to use BinaryReader — “Stream was not readable” reported. ReadByte failed in the same way. Cancel the CancellationToken cannot break the ReadAsync either. Setting read timeout is not supported in FileStream. And finally, the Thread.Abort is obsoleted and no use any more.
Is there any approach to cancel the running Read method of FileStream without exiting application?