Nimp
Nimp

Reputation: 471

Wait return from async task method

I'm beginner in code and I have spent hours of searching the solution to my problem.

I'm on a silverlight application which works with different web services and I call them with asynchronous method (I have no choice cause I am using silverlight), and the goal was too wait the return of my method before continue the execution of the application.

This is how my methods look (they are in a static class named Services) :

private static Task<ObservableCollection<Demande_GetNb_Result>> DemandeGetNbAsync()
{
    TaskCompletionSource<ObservableCollection<Demande_GetNb_Result>> tcs = new TaskCompletionSource<ObservableCollection<Demande_GetNb_Result>>();
    ABClient aBClient = new ABClient();
    aBClient.Demande_GetNbCompleted += (sender, e) =>
    {
        if (e.Error != null)
            tcs.TrySetException(e.Error);
        else if (e.Cancelled)
            tcs.TrySetCanceled();
        else
            tcs.TrySetResult(e.Result);
    };

    aBClient.Demande_GetNbAsync(((App)Application.Current).User.IdUser, true, true, true, (int)Constantes.Statut.Is_Waiting);
    return tcs.Task;
}

public static async Task StartFamille()
{
    ListInfos = await DemandeGetNbAsync(); // ListInfos is a Static variable on my Services class
}

and I call this method in other class like this :

var result = Services.StartFamille();

I want to wait until result has value before continuing the execution, but it doesn't work and I can't find a simple solution that I understand. The execution continue without waiting that a value is assigned to result.

Upvotes: 0

Views: 454

Answers (1)

RredCat
RredCat

Reputation: 5421

Your method returns Task. Try to add await operator.

var result = await Services.StartFamille();

Moreover, DemandeGetNbAsync method should return variable of ObservableCollection<Demande_GetNb_Result> type and use await operator as well.

Upvotes: 2

Related Questions