Async and await confusion

久未见 提交于 2019-12-10 11:33:19

问题


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:


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


来源:https://stackoverflow.com/questions/18718033/async-and-await-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!