CrashTestDummy
CrashTestDummy

Reputation: 145

How do you immediately cancel a firebase storage upload task?

The problem is that I want to know how to immediately cancel a FirebaseStorage UploadTask.

I have read https://firebase.google.com/docs/storage/unity/upload-files but it doesn't have any examples on how to cancel the UploadTask.

// Data in memory
var custom_bytes = new byte[] { ... };

// Create a reference to the file you want to upload
Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("images/rivers.jpg");

// Upload the file to the path "images/rivers.jpg"
rivers_ref.PutBytesAsync(custom_bytes)
  .ContinueWith ((Task<StorageMetadata> task) => {
    if (task.IsFaulted || task.IsCanceled) {
        Debug.Log(task.Exception.ToString());
        // Uh-oh, an error occurred!
    } else {
        // Metadata contains file metadata such as size, content-type, and download URL.
        Firebase.Storage.StorageMetadata metadata = task.Result;
        string download_url = metadata.DownloadUrl.ToString();
        Debug.Log("Finished uploading...");
        Debug.Log("download url = " + download_url);
    }
});

Upvotes: 1

Views: 1323

Answers (1)

Foggzie
Foggzie

Reputation: 9821

The PutBytesAsync() method returns a System.Task<T> and they natively support cancelation. I'd suggest reading the Task Cancellation Documentation as there are some caveats:

A successful cancellation involves the requesting code calling the CancellationTokenSource.Cancel method, and the user delegate terminating the operation in a timely manner. You can terminate the operation by using one of these options:

  • By simply returning from the delegate. In many scenarios this is sufficient; however, a task instance that is canceled in this way transitions to the TaskStatus.RanToCompletion state, not to the TaskStatus.Canceled state.

  • By throwing a OperationCanceledException and passing it the token on which cancellation was requested. The preferred way to do this is to use the ThrowIfCancellationRequested method. A task that is canceled in this way transitions to the Canceled state, which the calling code can use to verify that the task responded to its cancellation request.

Upvotes: 2

Related Questions