0

Need some advice on how to throw a TimeoutException after a certain time has passed and the method to Send Data to my fireStore db still not complete, due to internet loss or any other unexpected issue.

using the Plugin.CloudFirestore Plugin by f-Miyu.

The Code to send data to server.

    public async Task BackUpNotes(UserNotes n)
    {
        await CrossCloudFirestore.Current.Instance.Collection(FTxts.Notes).Document(n.ID)
                .SetAsync(new {
                    n.ID,
                    n.Title,
                    n.Details,
                    n.CreatedDate,
                    n.IsStarred,
                    n.LastEditDate,
                });
    }

//Called Here

    private async Task BackUpNotes()
    {
        if (IsBusy) return;
        IsBusy = true;
        int c = 0;
        var answer = await Application.Current.MainPage.DisplayAlert("Confirmation", "Back Up Current Notes?", "Yes", "No");
        if (answer)
        {
            foreach (var item in NotesCollection)
            {
                await CloudService.CS.BackUpNotes(item);
                item.IsBackedUp = true;
                await PlannerDataService.UpdateNote(item);
                c++;
                ToastMessageShort($"{c}/{NotesCollection.Count} Saved");
            }
            await GetNotes();
        }
        IsBusy = false;
    }
Pascal Jk
  • 23
  • 4

1 Answers1

0

Doesn't look like the library supports cancellation of Tasks, you can do a trick to add timeouts like:

var delayTask = Task.Delay(5000); // time out after 5 seconds
var backUpNotesTask = BackUpNotes(notes);

await Task.WhenAny(new [] { delayTask, backUpNotesTask });

This code will continue when the first of these tasks completes. This could be either the "time out" delayTask or the backUpNotesTask.

If you want to throw an exception if the first task to return isn't the backUpNotesTask you could check the result of WhenAny:

var winner = await Task.WhenAny(...

if (winner == delayTask)
    throw new TimeoutException();

Just keep in mind, this doesn't mean that BackUpNotes doesn't finish later

Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
  • thanks will attempt it now. – Pascal Jk Jun 06 '21 at 16:29
  • update: yah seems the task still runs in the background even if Exception was thrown Like you said it would defeating the purpose because that means users might double post items to my db due to the fact the Error didn't cancel the BackUpNotes. Is there no other work around so my BackUpNotes is Cancelled once my TimeOutException is Thrown.? – Pascal Jk Jun 06 '21 at 17:16
  • Unfortunately, not without the author adding some kind of cancellation mechanism to the library. – Cheesebaron Jun 06 '21 at 17:21
  • Ok Thanks a lot will keep trying to find work arounds. – Pascal Jk Jun 06 '21 at 20:13