I'm using the DataWriter and DataReader interfaces.
These classes have the IDisposable interface implemented, therefore I wrap them around the using
keyword:
using(var datareader = new DataReader(SerialPortInputStream))
{
CancellationTokenSource cancellation = new CancellationTokenSource();
//Timeout
cancellation.CancelAfter(1000);
//...
datareader.LoadAsync(120).AsTask(cancellation.Token);
//Some fancy methods
...
//Last step: Detach the InputStream to use it again
datareader.DetachStream();
}
This thread here is saying that if an Exception (here a "TaskCancelledException"
happens inside a using statement, the object gets disposed. Now, the problem is with the UWP-DataReader
and DataWriter
: They will close the underlying stream if the object gets disposed. To prevent that I've to call datareader.DetachStream() and then dispose.
We cannot use the DataReader/DataWriter with a using
statement when we need the underlying InputStream/Outputstream later again.
Is this conclusion correct or are there other ways to handle this situation?