有网络API控制器等待的IAsyncResult之前完成? [英] Have Web API controller wait for IAsyncResult before completing?

查看:109
本文介绍了有网络API控制器等待的IAsyncResult之前完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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){}


解决方案

您可以让你的方法异步任务&LT;串&GT; ,创建一个任务基于代理类的<​​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 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);   
}

这篇关于有网络API控制器等待的IAsyncResult之前完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆