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

后端 未结 3 484
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 10:09

    As long as you return a Task that completes somehow (whether in a thread or asynchronously), you would support the async model..

    Having a Task execute asynchronously is another story. If you had access to the async keyword and the API you could simply base your method on async calls to other, already supplied async methods. But in this case, you have to hand-craft your async Tasks.

    There might be better ways to do it, but the most elegant way I can see (and have used) is to utilize System.Threading.Tasks.TaskCompletionSource to construct a task, use Begin/End model of asynchronous methods to execute whatever you need to execute. Then, when you have the result on hand, post it to the previously constructed Task instance using your completion source.

    It will certainly be asynchronous, just not as fancy as the ones in upcoming release.

    Disclaimer: I'm no way near an expert on this. Just made some experiments on.

提交回复
热议问题