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

问题描述

我有一个Web API控制器。它调用返回一个IAsyncResult的方法。当我打电话控制器,我得到的错误

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之前完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:37