Async and await confusion

非 Y 不嫁゛ 提交于 2019-12-06 11:45:33

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