Jefferson
Jefferson

Reputation: 93

Xamarin Safe way to call async task

I have this one section where I want to wait to make sure this task is completed. I have added the task.wait but it seems that the await in the task are not getting completed.

Is this getting me into a deadlock ? is there a better way to do this?

Task task = Task.Run(() => DataSynchronize.SyncLinks());
task.Wait();
if (task.Status == TaskStatus.RanToCompletion)
{
Preferences.Set("IsUpdate", "True");
}

Model

public static async Task<Status> SyncLinks()

All Other section use this

await DataSynchronize.SyncLinks();

Upvotes: 0

Views: 131

Answers (1)

Nkosi
Nkosi

Reputation: 247088

Too long for a comment so adding here

await the task and check its status

Task<Status> task = DataSynchronize.SyncLinks();
await task;
if (task.Status == TaskStatus.RanToCompletion) {
    Preferences.Set("IsUpdate", "True");
}

Or better yet

just await the call

Status status = await DataSynchronize.SyncLinks();
if(...some condition based on status)
    Preferences.Set("IsUpdate", "True");

All in all, try to avoid mixing blocking calls like .Result or .Wait() that can potentially cause deadlocks.

Upvotes: 2

Related Questions