Can you explain why the exception is not caught if I do not await an async task?

巧了我就是萌 提交于 2019-12-05 21:52:51

In your first button1_Click implementation, you are ignoring the result of the Task returned by TestWork.

In your modified version, the await checks for an Exception and propogates it for you to catch.

In fact, the compiler warning you are seeing is normally important. If TestWork actually ran something on a different thread, then because the wrapper Task in your first implementation doesn't wait for TestWork to complete, it would just complete itself as soon as TestWork had started.

Writing it this way makes it clearer:

Task task = Task.Run( () =>
    {
        Task t = TestWork();
        // ignore t
    }
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!