How to write an “awaitable” method?

后端 未结 6 1892
南笙
南笙 2020-12-07 13:20

I\'m finally looking into the async & await keywords, which I kind of "get", but all the examples I\'ve seen call async methods in the .Net framework, e.g. thi

6条回答
  •  佛祖请我去吃肉
    2020-12-07 13:34

    It's as simple as

    Task.Run(() => ExpensiveTask());
    

    To make it an awaitable method:

    public Task ExpensiveTaskAsync()
    {
        return Task.Run(() => ExpensiveTask());
    }
    

    The important thing here is to return a task. The method doesn't even have to be marked async. (Just read a little bit further for it to come into the picture)

    Now this can be called as

    async public void DoStuff()
    {
        PrepareExpensiveTask();
        await ExpensiveTaskAsync();
        UseResultsOfExpensiveTask();
    }
    

    Note that here the method signature says async, since the method may return control to the caller until ExpensiveTaskAsync() returns. Also, expensive in this case means time-consuming, like a web request or similar. To send off heavy computation to another thread, it is usually better to use the "old" approaches, i.e. System.ComponentModel.BackgroundWorker for GUI applications or System.Threading.Thread.

提交回复
热议问题