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

后端 未结 3 485
佛祖请我去吃肉
佛祖请我去吃肉 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:22

    As others have stated, you start by having a method return Task or Task. This is sufficient to await its result in .NET 4.5.

    To have your method fit in as well as possible with future asynchronous code, follow the guidelines in the Task-based Asynchronous Pattern document (also available on MSDN). It provides naming conventions and parameter recommendations, e.g., for supporting cancellation.

    For the implementation of your method, you have a few choices:

    • If you have existing IAsyncResult-based asynchronous methods, use Task.Factory.FromAsync.
    • If you have another asynchronous system, use TaskCompletionSource.

提交回复
热议问题