Calling async methods from non-async code

后端 未结 4 1395
青春惊慌失措
青春惊慌失措 2020-11-28 19:25

I\'m in the process of updating a library that has an API surface that was built in .NET 3.5. As a result, all methods are synchronous. I can\'t change the API (i.e., conver

4条回答
  •  抹茶落季
    2020-11-28 20:05

    I just went thru this very thing with the AWS S3 SDK. Used to be sync, and I built a bunch of code on that, but now it's async. And that's fine: they changed it, nothing to be gained by moaning about it, move on.
    So I need to update my app, and my options are to either refactor a large part of my app to be async, or to "hack" the S3 async API to behave like sync.
    I'll eventually get around to the larger async refactoring - there are many benefits - but for today I have bigger fish to fry so I chose to fake the sync.

    Original sync code was
    ListObjectsResponse response = api.ListObjects(request);
    and a really simple async equivalent that works for me is
    Task task = api.ListObjectsV2Async(rq2);
    ListObjectsV2Response rsp2 = task.GetAwaiter().GetResult();

    While I get it that purists might pillory me for this, the reality is that this is just one of many pressing issues and I have finite time so I need to make tradeoffs. Perfect? No. Works? Yes.

提交回复
热议问题