Creating an async method in .NET 4.0 that can be used with “await” in .NET 4.5

后端 未结 3 477
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-23 09:53

I have a .NET project that uses C# in .NET 4.0 and VS2010.

What I would like to do is add some async overloads to my library to make doing async programming easier f

3条回答
  •  情话喂你
    2020-12-23 10:06

    The simplest way to do this is to return a Task or a Task. That will be enough.

    However this only makes sense if your method really executes asynchronously.

    I also recommend that you follow the usual pattern of naming them like AbcAsync ("Async" suffix). Your callers will not notice any difference to an async method created with C# 5 (because there is none).

    Tip: Just adding async to the method does nothing. Your method will execute sequentially and return a completed task. Making the method return a task must serve a certain purpose - usually this is done because the method inherently executes asynchronously (like a web-service call or file IO).

    If your method only contains computation but no IO (or only blocking IO) it is usually better not to make it async because you gain nothing doing that. Async methods do not always execute on a separate thread. If that last sentence surprised you, you may want to dig a little into this topic.

提交回复
热议问题