         dispatch_queue.async {
             var timedOut: Bool = false
             self.dataReceivedLock.lock()
-            while (self.dataReceived.count == 0 || self.dataReceived.count < minBytes) && !timedOut {
+            while (self.dataReceived.count == 0 || self.dataReceived.count < minBytes) && !timedOut && !self.endEncountered {
                 self.dataReceivedLock.unlock()
                 Thread.sleep(forTimeInterval: 0.1)
                 if let error = inputStream.streamError {

            streamDelegate?.urlSession?(_underlyingSession, task: self, didCompleteWithError: error)
        }
        
        if aStream == inputStream && eventCode.contains(.hasBytesAvailable) {
            while (inputStream!.hasBytesAvailable) {
                var buffer = [UInt8](repeating: 0, count: 2048)

        return FileProviderStreamTask.streamTasks[_taskIdentifier]
    }
    
    /// The end of the stream has been reached.
    private var endEncountered: Bool = false
    
    /// Trust all certificates if `disableEvaluation`, Otherwise validate certificate chain.
    public var serverTrustPolicy: ServerTrustPolicy = .performDefaultEvaluation(validateHost: true)
    
