简体   繁体   中英

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 :

  • Cancelling after multiple times (eg 1 second, 10 seconds etc)
  • Immediately cancelling with the token after starting the upload Using
  • UploadFromByteArrayAsync() instead of UploadFromStreamAsync() Using
  • BeginUploadFromStream() with EndUploadFromStream()

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); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM