0

I'm writing a UWP (WinRT) solution that downloads a file from a server and saves to disc while indicating progress. For this purposes I extended the IAsyncOperationWithProgress method.

My problem is that at a single line:

while ((await responseStream.ReadAsync(streamReadBuffer, bufferLength, InputStreamOptions.None)).Length > 0 && !token.IsCancellationRequested)

I wait for content to be read from the stream. If the connection is lost, this line will wait indefinitely until a connection has been re-established.

How, for UWP do I either assign a time-out to an Http request, or alternatively, cancel a single task?

My extended IAsyncOperationWithProgress:

private static IAsyncOperationWithProgress<HttpDownloadStatus, DownloadResponse> DownloadAsyncWithProgress(this HttpClient client, HttpRequestMessage request, CancellationToken cancelToken, StorageFile fileToStore)
    {
        const uint bufferLength = 2048;
        var progressResponse = new DownloadResponse
        {
            File = fileToStore,
            DownloadStatus = HttpDownloadStatus.Started,
            BytesRecieved = 0,
            Progress = 0.00
        };
        string result = string.Empty;
        HttpDownloadStatus returnStatus = HttpDownloadStatus.Busy;
        IBuffer streamReadBuffer = new Windows.Storage.Streams.Buffer(bufferLength);

        var operation = client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);

            return AsyncInfo.Run<HttpDownloadStatus, DownloadResponse>((token, progress) =>
                Task.Run(async () =>
                {
                    try
                    {
                        if (cancelToken != CancellationToken.None) token = cancelToken;
                        HttpResponseMessage respMessage;
                        try
                        {
                            respMessage = await operation;
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error sending download request - " + ex.Message);
                        }
                        progressResponse.TotalBytes = Convert.ToInt64(respMessage.Content.Headers.ContentLength);
                        using (var responseStream = await respMessage.Content.ReadAsInputStreamAsync())
                        {
                            using (var fileWriteStream = await fileToStore.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                token.ThrowIfCancellationRequested();
                                while ((await responseStream.ReadAsync(streamReadBuffer, bufferLength, InputStreamOptions.None)).Length > 0 && !token.IsCancellationRequested)
                                {

                                    while(DownloadManager.ShouldPauseDownload && DownloadManager.CurrentDownloadingBook.FileName == fileToStore.Name)
                                    {
                                        if (token.IsCancellationRequested)
                                            break;
                                    }

                                    progressResponse.DownloadStatus = HttpDownloadStatus.Busy;
                                    if (token.IsCancellationRequested)
                                    {
                                       // progressResponse.DownloadStatus = HttpDownloadStatus.Cancelled;
                                       // returnStatus = HttpDownloadStatus.Cancelled;
                                        break;
                                    }

                                    ;
                                    await fileWriteStream.WriteAsync(streamReadBuffer);
                                    progressResponse.BytesRecieved += (int)streamReadBuffer.Length;
                                    progressResponse.Progress = (progressResponse.BytesRecieved / (double)progressResponse.TotalBytes) * 100;
                                    //Only give response when close to a byte
                                    if (progressResponse.BytesRecieved % 1048576 == 0)
                                    {
                                        Debug.WriteLine("Should be 1 meg: " + progressResponse.BytesRecieved);
                                        progress.Report(progressResponse);
                                    }
                                } //while (offset < contentLength);
                                if (token.IsCancellationRequested)
                                {
                                    progressResponse.DownloadStatus = HttpDownloadStatus.Cancelled;
                                    returnStatus = HttpDownloadStatus.Cancelled;
                                }

                            }
                        }
                        if(returnStatus == HttpDownloadStatus.Busy) //only set it if it was still legitimately busy
                            returnStatus = HttpDownloadStatus.Complete;

                        return returnStatus;
                    }
                    catch (TaskCanceledException tce)
                    {
                        Debug.WriteLine("CANCEL - Download cancellation token caught from within task");
                        return HttpDownloadStatus.Cancelled;
                    }
                }, token));


    }

How the above code is called:

HttpClient httpClient = new HttpClient(PFilter);

try
{
DownloadResponse downloadResponse = new DownloadResponse { File = fileToSave, DownloadStatus = HttpDownloadStatus.Busy };
CancellationToken cancelToken = m_CancellationSource.Token;

HttpRequestMessage requestMsg = new HttpRequestMessage(HttpMethod.Get, downloadUri);

IAsyncOperationWithProgress<HttpDownloadStatus,DownloadResponse> operationWithProgress = httpClient.DownloadAsyncWithProgress(requestMsg, cancelToken, fileToSave);

operationWithProgress.Progress = new AsyncOperationProgressHandler<HttpDownloadStatus, DownloadResponse>((result, progress) => { progressDelegate(progress); });

var response = await operationWithProgress;

downloadResponse.DownloadStatus = response;

if (response == HttpDownloadStatus.Complete)
{
    return HttpWebExceptionResult.Success;
}
else if (response == HttpDownloadStatus.ConnectionLost)
    return HttpWebExceptionResult.ConnectionFailure;
else if (response == HttpDownloadStatus.Cancelled)
    return HttpWebExceptionResult.RequestCanceled;
else
    return HttpWebExceptionResult.UnexpectedError;



}
catch (TaskCanceledException tce)
{
    Debug.WriteLine("CANCEL - token caught from StartDownloadAsync ");
    return HttpWebExceptionResult.RequestCanceled;
}
catch (Exception ex)
{
    return HttpWebExceptionResult.UnexpectedError;
}
Vincent
  • 3,656
  • 1
  • 23
  • 32
nico van vuuren
  • 105
  • 1
  • 8
  • I always find it much cleaner to put my logic in pure `async`/`await` methods and then have a separate `AsyncOperation` wrapper method. – Stephen Cleary Jul 03 '17 at 14:09
  • Can you please elaborate w.r.t. the example above? How would you wrap the AsyncOperation separately? – nico van vuuren Jul 03 '17 at 17:28
  • 1
    I mean have all the logic using the more natural `async`/`await`, which will result in a (private) `Task DownloadWithProgressAsync(IProgress)`, and then have a (public) `IAsyncOperationWithProgress DownloadAsyncWithProgress` that just wraps the other method. – Stephen Cleary Jul 03 '17 at 19:56
  • `If the connection is lost, this line will wait indefinitely ` If it waits indefinitely. You should cancel this task by `CancellationTokenSource.CancelAfter (timespan)` – Timo Jul 06 '17 at 02:59

1 Answers1

0

If you want to cancel an IAsyncOperation operation from the WinRT API, you will need to convert it to a Task first and then provides a CancellationToken that will expire after your timeout duration.

In this sample, inputStream.ReadAsync() will be cancelled if it did not complete within 2 seconds:

var timeoutCancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
var response = await inputStream.ReadAsync(buffer, bufferLength, InputStreamOptions.None).AsTask(timeoutCancellationSource.Token);

If you do not want to wait for the 2 seconds, you can call Cancel() on the CancellationTokenSource anytime you want.

timeoutCancellationSource.Cancel();
Vincent
  • 3,656
  • 1
  • 23
  • 32