Have Web API controller wait for IAsyncResult before completing?

一笑奈何 提交于 2019-12-11 17:34:00

问题


I have a Web API controller. It calls a method that returns an IAsyncResult. When I call the controller, I get the error

An asynchronous module or handler completed while an asynchronous operation was still pending.

How do I get the controller to wait for the asyncresult?

I was planning to use await, but I may just not have figured out the syntax for this use case.

I haven't found an existing answer on SO.

I'm using c# 4.5

[HttpGet]
[Route("GetGridDataAsync")]
public string GetGridDataAsync()
{
        var proxy = new Proxy();
        return proxy.BeginGetDataAsync("test", ar => proxy.EndGetDataAsync(ar));             
}

public IAsyncResult BeginGetDataAsync(string r, AsyncCallback callback){}

public DataResponse[] EndGetDataAsync(IAsyncResult asyncResult){}

回答1:


You can make your method an async Task<string>, create a Task based on the Async methods in the Proxy class and await that

Example:

public async Task<string> GetGridDataAsync()
{
    var proxy = new Proxy();
    return await Task.Factory.FromAsync(proxy.BeginGetDataAsync, proxy.EndGetDataAsync, "test", null);   
}


来源:https://stackoverflow.com/questions/25127183/have-web-api-controller-wait-for-iasyncresult-before-completing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!