有网络API控制器等待的IAsyncResult之前完成? [英] Have Web API controller wait for IAsyncResult before completing?
问题描述
我有一个Web API控制器。它调用返回一个IAsyncResult的方法。当我打电话控制器,我得到的错误
而异步操作仍然悬而未决的异步模块或处理程序完成。
块引用>我怎么控制器等待asyncresult?
我正打算使用的await,但我可能只是没有想出了这个用例的语法。
我还没有发现对SO现有的应答。
我使用C#4.5
[HTTPGET]
〔路线(GetGridDataAsync)]
公共字符串GetGridDataAsync()
{
VAR代理=新代理();
返回proxy.BeginGetDataAsync(测试,AR => proxy.EndGetDataAsync(AR));
}公众的IAsyncResult BeginGetDataAsync(串R,AsyncCallback的回调){}公共DataResponse [] EndGetDataAsync(IAsyncResult的asyncResult){}
解决方案您可以让你的方法异步
任务<串>
,创建一个任务
基于代理
类的<code>异步方法和等待
是例如:
公共异步任务&LT;串GT; GetGridDataAsync()
{
VAR代理=新代理();
返回等待Task.Factory.FromAsync(proxy.BeginGetDataAsync,proxy.EndGetDataAsync,测试,NULL);
}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){}
解决方案You can make your method an async
Task<string>
, create aTask
based on theAsync
methods in theProxy
class andawait
thatExample:
public async Task<string> GetGridDataAsync() { var proxy = new Proxy(); return await Task.Factory.FromAsync(proxy.BeginGetDataAsync, proxy.EndGetDataAsync, "test", null); }
这篇关于有网络API控制器等待的IAsyncResult之前完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!