I want to cancel a Read call that has a very long delay after establishing an HTTP connection.
Will it be possible to cancel quickly using Cancellation.Register(() => stream.Close()) as shown below?
Please let me know if there is a correct cancellation method.
Current method in use (simplified)
try
{
var stream = response.GetResponseStream();
using var registration = canceltoken.Register(()=> stream.Close());
while(canceltoken.IsCancellationRequested == false)
{
var data = stream.Read(buffer, 0, length);
...
}
}
catch(Exception) when (cancelToken.IsCancellationRequested)
{
canceled = true;
}
catch(Exception ex)
{
error = ex.Message;
}