Have Web API controller wait for IAsyncResult befo

2019-08-29 12:12发布

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条回答
做个烂人
2楼-- · 2019-08-29 12:37

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);   
}
查看更多
登录 后发表回答