2

hello friend i got confusion in working of async and await keywords.actually i have written this async function

private static async Task FillAssignmentStudentTableFromExtraUsers(int assignmentId, List<JToken> lstOfExtraUser)
    {
        await CreatTable.CreatAssignmentStudentTable();

        foreach (var item in lstOfExtraUser)
        {
            assignmentStudentModel obj = new assignmentStudentModel()
            {
                AssignmentId = assignmentId,
                studentId = (int.Parse)(item.SelectToken("id").ToString()),
                name = item.SelectToken("name").ToString(),
                username = item.SelectToken("username").ToString()
            };

            await App.conn.InsertAsync(obj);
        }

    }

inside part is just unnecessary ...here i have called this function in some button click without await keyword..

 private void GrdReport_Tapped_1(object sender, TappedRoutedEventArgs e)
    {
        FillAssignmentStudentTableFromExtraUsers(3,listofjtoken);
    }

this method will run asynchronously that is ok but some where else where i want to use data filled by this method ..i wanted to be sure that it should filled all the data before o do any calculation..so i thought of just putting await before it thr like this..

await FillAssignmentStudentTableFromExtraUsers(3,listofjtoken);

but i am thinking that the above statement make it run again whether await for the previous call..any suggestion how wait for the first call to be completed..or my assumption is wrong..any help is appreciated..

loop
  • 9,002
  • 10
  • 40
  • 76
  • I'd implement some "I'm busy" and "I'm no longer busy" methods, to invoke before and after the critical awaits (i.e. you could disable and re-enable some controls, or set some flags ... I usually do this to disable/enable buttons around the application) – Alex Sep 10 '13 at 11:53
  • "some where else where i want to use data": what triggers this? Is this an user triggered event (e.g., button click)? – dcastro Sep 10 '13 at 11:57

1 Answers1

1

An easy way to detect whether the task has already run is to save the task as a private field, and await it whenever you need to check its status.

public class MyClass
{
    private Task _task;
    private static async Task FillAssignmentStudentTableFromExtraUsers(int assignmentId, List<JToken> lstOfExtraUser)
    {
        //...
    }

    private void GrdReport_Tapped_1(object sender, TappedRoutedEventArgs e)
    {
        //"fire and forget" task
        _task = FillAssignmentStudentTableFromExtraUsers(3,listofjtoken);
    }

    private void WorkWithData()
    {
        if(_task != null)
            await _task;

        //do something
    }

}

By the time you call await _task, one of the following two things will happen:

  • if the task is still running, you will wait (asynchronously, of course) for it to finish.
  • if the task has completed, your method will carry on
dcastro
  • 66,540
  • 21
  • 145
  • 155