Jonathan772
Jonathan772

Reputation: 39

UploadFromStreamAsync Cancellation Token not working

Expected behaviour:

Looking at my internet usage in task manager after running should see a spike in upload for around 5 seconds and then a drop back to normal levels.

Result:

Upload speed spikes for a lot longer (closer to a minute or more, indicative of the full file being uploaded)

Tried:

Although I can quite easily cancel a download using the CancellationToken, no matter what I do, I can't cancel this upload. Also, weirdly, searching online, I can't find any instance of anyone else having problems cancelling an upload.

            _connectionString = "xxx";                

            if (_connectionString != "")
            {
                _storageAccount = CloudStorageAccount.Parse(_connectionString);
                _blobClient = _storageAccount.CreateCloudBlobClient();
            }

            string ulContainerName = "speedtest";
            string ulBlobName = "uploadTestFile" + DateTime.UtcNow.ToLongTimeString();

            CloudBlobContainer container = _blobClient.GetContainerReference(ulContainerName);
            CloudBlockBlob ulBlockBlob = container.GetBlockBlobReference(ulBlobName);

            CreateDummyDataAsync(_fileUploadSizeMB);

            byte[] byteArray = System.IO.File.ReadAllBytes(_filePath + "dummy_upload");

            ulBlockBlob.UploadFromStreamAsync(new MemoryStream(byteArray), _ulCancellationTokenSource.Token);
            _ulCancellationTokenSource.CancelAfter(5000); 

Upvotes: 0

Views: 453

Answers (1)

Jonathan772
Jonathan772

Reputation: 39

To anyone that ends up in this situation and can't get the cancellationToken to work... the workaround I eventually used was

            BlobRequestOptions timeoutRequestOptions = new BlobRequestOptions()
        {
            // Allot 10 seconds for this API call, including retries
            MaximumExecutionTime = TimeSpan.FromSeconds(10)
        };

Then include the timeoutRequestOptions in the method arguments:

ulBlockBlob.UploadFromStreamAsync(new MemoryStream(byteArray), new AccessCondition(),
                                                   timeoutRequestOptions,
                                                   new OperationContext(),
                                                   new progressHandler(), cancellationToken.Token);

This will force the API call to timeout after a certain time.

Upvotes: 2

Related Questions