Async and await confusion

2019-05-28 14:34发布

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..

1条回答
啃猪蹄的小仙女
2楼-- · 2019-05-28 14:46

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
查看更多
登录 后发表回答