c# - How to implement timeout on a .NET Stream when timeouts are not supported on this stream -
i trying read/write bytes to/from bluetooth printer using xamarin android in c#. making use of system.io.stream
this. unfortunately, whenever try use readtimeout
, writetimeout
on streams following error:
message = "timeouts not supported on stream."
i don't want stream.read()
, stream.write()
calls block indefinitely. how can solve this?
you expose method cancellation token api can easliy consumed.
one of cancellationtokensource constructors takes timespan parameter. cancellationtoken on other hand exposes register method allows close stream , reading operation should stop exception being thrown.
method call
var timeout = timespan.parse("00:01:00"); var cancellationtokensource = new cancellationtokensource(timeout); var cancellationtoken = cancellationtokensource.token; await readasync(stream, cancellationtoken);
method implementation
public async task readasync(stream stream, cancellationtoken cancellationtoken) { using (cancellationtoken.register(stream.dispose)) { var buffer = new byte[1024]; var read = 0; while ((read = await stream.readasync(buffer, 0, buffer.length)) > 0) { // stuff read data } } }
the following code dispose stream if times out
more can found here.
edit:
changed .close() .dispose() since no longer available in pcls .close() vs .dispose()
Comments
Post a Comment